我正在尝试测试方法是否在同一个类中调用另一个方法。示例:
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);
}
}
但是,如果我尝试对类本身进行mockito验证:
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”)是否被调用?
答案 0 :(得分:1)
这应该有效。
@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
方法时才有效。
答案 1 :(得分:0)
您不应该模拟测试对象,而是可以间谍:
select * from [dbo].[aTable] where [aDate] >= '@{formatDateTime(adddays(pipeline().parameters.windowStart, -5), 'yyyy-MM-dd HH:mm')}'
或
@RunWith(SpringJUnit4ClassRunner.class)
public class FooTest {
@Test
public void testBazCalledFromBar(){
Foo foo = Mockito.spy(Foo.class);
foo.bar("callBaz");
Mockito.verify(foo).baz("callBaz");
}
}