gpt4 book ai didi

java - Mockito:如何测试调用了构造函数?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:04:11 28 4
gpt4 key购买 nike

我正在使用 Mockito 测试我的 Java 应用程序中的方法。

如何测试构造函数是否被调用过一次?

我正在尝试进行与此类似的验证:

verify(myClass, times(1)).doSomething(anotherObject);

但我无法验证是否调用了构造函数,因为它没有类似于例如doSomething().

最佳答案

您可以使用 Mockito 和 PowerMockito 来完成。

假设您有一个带有构造函数的 ClassUnderTest

public class ClassUnderTest {
String name;
boolean condition;

public ClassUnderTest(String name, boolean condition) {
this.name = name;
this.condition = condition;
init();
}

...
}

还有另一个调用该构造函数的类

public class MyClass {

public MyClass() { }

public void createCUTInstance() {
// ...
ClassUnderTest cut = new ClassUnderTest("abc", true);
// ...
}

...
}

在测试课上我们可以...

(1) 使用 PowerMockRunner 并在 PrepareForTest 注释中引用上面的两个目标类:

@RunWith(PowerMockRunner.class)
@PrepareForTest({ ClassUnderTest.class, MyClass.class })
public class TestClass {

(2)拦截构造函数返回一个mock对象:

@Before
public void setup() {
ClassUnderTest cutMock = Mockito.mock(ClassUnderTest.class);
PowerMockito.whenNew(ClassUnderTest.class)
.withArguments(Matchers.anyString(), Matchers.anyBoolean())
.thenReturn(cutMock);
}

(3) 验证构造函数调用:

@Test
public void testMethod() {
// prepare
MyClasss myClass = new MyClass();

// execute
myClass.createCUTInstance();

// checks if the constructor has been called once and with the expected argument values:
String name = "abc";
String condition = true;
PowerMockito.verifyNew(ClassUnderTest.class).withArguments(name, condition);
}

关于java - Mockito:如何测试调用了构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38847558/

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