简体   繁体   中英

How do I test this static member in a class with private constructor?

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?

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
       .....
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM