gpt4 book ai didi

java - 如何在具有私有(private)构造函数的类中测试此静态成员?

转载 作者:行者123 更新时间:2023-12-01 16:39:09 25 4
gpt4 key购买 nike

所以我的类(class)是:

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

我正在尝试使用 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);

此行失败并表示将 MyClass 构造函数包设为私有(private)。有什么方法可以做到这一点而不这样做吗?

最佳答案

使用 set 方法将模拟的 myObject 添加到 MyClass 并编写测试,如下所示:

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

关于java - 如何在具有私有(private)构造函数的类中测试此静态成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61899848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com