Issue
So my class is:
public final class MyClass {
private static MyObject myObject;
public static void setMyObject(MyObject myObject) {
MyClass.myObject = myObject;
}
private MyClass(MyObject myObject){
setMyObject(myObject);
}
public static Optional<Object2> getObject2(params) {
Optional<Object2> object2 = myObject.execute(params);
return object2;
}
I'm trying to test with Junit
@RunWith(MockitoJUnitRunner.class)
public class MyClassTest {
@Mock
private MyObject myObject;
private MyClass myClass;
@Before
public void initialize() {
MockitoAnnotations.initMocks(this);
}
@Test
public void test1() {
Mockito.doReturn(Optional.empty()).when(myObject).executeQueryWithArgument(any);
myclass = new Myclass(myObject);
}
}
myclass = new Myclass(myObject);
This line fails and says make MyClass constructor package private. Is there any way to do this without doing that?
Solution
Add mocked myObject
to the MyClass
using the set method and write the test, like this:
@RunWith(MockitoJUnitRunner.class)
public class MyClassTest {
@Mock
private MyObject myObject;
private MyClass myClass;
@Before
public void setUp() {
MyClass.setMyObject(myObject);
}
@Test
public void shouldDoSomething() {
// Arrange
Mockito.doReturn(Optional.empty()).when(myObject).executeQueryWithArgument(any);
// Act
Optional<Object2> actual = myClass.getObject2(.....);
// Assert
.....
}
}
Answered By - heaprc