我正在尝试测试一个方法是否调用同一类中的另一个方法。 示例:
public class Foo {
public void bar(String a){
switch(a) {
case "callBaz":
baz(a);
break;
case "callBat":
bat(a);
break;
default:
System.out.println("Input was " + a);
}
}
public void baz(String b){
System.out.println(b);
}
public void bat(String c){
System.out.println(c);
}
}
但是,如果我尝试在类本身上进行模拟验证:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
public class FooTest {
@Test
public void testBazCalledFromBar(){
Foo foo = new Foo();
foo.bar("callBaz");
Mockito.verify(foo).baz("callBaz");
}
}
我得到例外:
org.mockito.exceptions.misusing.NotAMockException:
Argument passed to verify() is of type Foo and is not a mock!
Make sure you place the parenthesis correctly!
See the examples of correct verifications:
verify(mock).someMethod();
verify(mock, times(10)).someMethod();
verify(mock, atLeastOnce()).someMethod();
使用模拟时: ...
@RunWith(SpringJUnit4ClassRunner.class)
public class FooTest {
@Test
public void testBazCalledFromBar(){
Foo fooMock = Mockito.mock(Foo.class);
fooMock.bar("callBaz");
Mockito.verify(fooMock).baz("callBaz");
}
}
我得到例外:
Wanted but not invoked:
foo.baz("callBaz");
-> at com.mn.stagportal.view.employee.FooTest.testBazCalledFromBar(FooTest.java:15)
However, there were other interactions with this mock:
foo.bar("callBaz");
-> at com.mn.stagportal.view.employee.FooTest.testBazCalledFromBar(FooTest.java:13)
有谁知道如何测试是否调用了 baz("callBaz"(?
这应该有效。
@RunWith(SpringJUnit4ClassRunner.class)
public class FooTest {
@Test
public void testBazCalledFromBar(){
Foo fooMock = Mockito.mock(Foo.class);
doCallRealMethod().when(fooMock).bar(anyString());
fooMock.bar("callBaz");
Mockito.verify(fooMock).baz("callBaz");
}
}
问题是,由于 fooMock 是一个模拟,当它遇到这条线时
fooMock.bar("callBaz");
它不知道该怎么办。你需要告诉Mockito,你是想模拟方法调用还是想调用真正的方法。
仅当代码流转到此实际方法并调用baz
方法时,验证才能工作。
你不应该嘲笑被测试的对象,你可以监视:
@RunWith(SpringJUnit4ClassRunner.class)
public class FooTest {
@Test
public void testBazCalledFromBar(){
Foo foo = Mockito.spy(Foo.class);
foo.bar("callBaz");
Mockito.verify(foo).baz("callBaz");
}
}
或
@RunWith(SpringJUnit4ClassRunner.class)
public class FooTest {
@Test
public void testBazCalledFromBar(){
Foo foo = Mockito.spy(new Foo(/* params */));
foo.bar("callBaz");
Mockito.verify(foo).baz("callBaz");
}
}