我已经发布了与我使用Mockito.verify()或doNothing()编写用于创建方法的测试用例的要求相匹配的示例代码。我想验证ClassB的create()方法时是否返回true或doNothing()而不返回DB。我尝试了自己不适合我的不同方式,并在Test Class中对输出进行了注释。任何帮助将不胜感激
public class ClassA {
ClassB b=new ClassB();
public TestPojo create(TestPojo t) {
TestPojo t2= b.create(t);
return t2;
}
}
public class ClassB {
public TestPojo create(TestPojo t) {
System.out.println("class b");
return t;
}
}
public class TestPojo {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
public class ClassTest {
@Test
public void testCreate_1()
throws Exception {
ClassA testA=Mockito.spy(new ClassA());
ClassB testB=Mockito.spy(new ClassB());
TestPojo test=Mockito.spy(new TestPojo());
test.setId(1);
//Mockito.verifyZeroInteractions(testB); -- testcase is passed but executing ClassB method but this not our intension
//Mockito.verify(testB).create(test); --error output : Wanted but not invoked
//Mockito.doNothing().when(testB).create(test); --error output : Only void methods can doNothing()!
TestPojo act=testA.create(test);
//System.out.println(act.getId());
}
@Before
public void setUp()
throws Exception {
}
@After
public void tearDown()
throws Exception {
// Add additional tear down code here
}
public static void main(String[] args) {
new org.junit.runner.JUnitCore().run(ClassTest.class);
}
}
最佳答案
它对您不起作用,因为实际上没有将创建的实例testB
分配给b
中的字段ClassA
。要使其正常工作,您需要设置模拟实例并添加验证检查。
@Test
public void testCreate_1() throws Exception {
ClassA testA = Mockito.spy(new ClassA());
ClassB testB = Mockito.mock(ClassB.class);
// set spied instance to testA
testA.b = testB;
// you don't need to spy on test, as you're not verifying anything on it
TestPojo test = new TestPojo();
test.setId(1);
// execute your test method
TestPojo act = testA.create(test);
// verify that required create method with proper argument was called on testB
Mockito.verify(testB, Mockito.times(1)).create(Matchers.eq(test));
// verify that nothing else executed on testB
Mockito.verifyNoMoreInteractions(testB);
}
希望能帮助到你!