[英]Mockito - clear argument captor pr
My problem is best described by a simple example. 我的问题最好通过一个简单的例子来描述。 Here is my class:
这是我的班级:
public class App
{
void doFirst(String s){
if(s.equals("hello")){
return;
}
doSecond(s);
}
void doSecond(String s){
}
}
And here is my test: 这是我的测试:
public void testApp() {
App a = spy(new App());
ArgumentCaptor<String> argument = ArgumentCaptor.forClass(String.class);
doNothing().when(a).doSecond(argument.capture());
a.doFirst("bye");
assertEquals("bye", argument.getValue());
a.doFirst("hello");
assertEquals(null, argument.getValue());
}
The problem is that that second assert fails becauseargument.getValue() has the value from previos call to doFirst. 问题是第二个断言失败,因为argument.getValue()具有来自previos调用doFirst的值。 Can i somehow clear argument after first assertion so it will be null by the time it reaches second one?
我可以在第一次断言后以某种方式清除参数,所以当它到达第二个时它将为空吗?
Thank you. 谢谢。
It looks to me like you are testing two different conditions - 在我看来,你正在测试两种不同的条件 -
doSecond
gets called with the right argument when s
is not "hello"
s
不是"hello"
时,用正确的参数调用doSecond
doSecond
does not get called, when s
is "hello"
s
是"hello"
时, doSecond
不被调用 That should be two separate tests. 这应该是两个单独的测试。
Also, don't use an ArgumentCaptor
and assertEquals
. 另外,不要使用
ArgumentCaptor
和assertEquals
。 This is what verify
is for. 这就是
verify
目的。 You could write your test class like this. 您可以像这样编写测试类。
@RunWith(MockitoJUnitRunner.class)
public class AppTest {
@Spy App toTest;
@Test
public void doSecondIsCalledWhenArgumentIsNotHello() {
toTest.doFirst("bye");
verify(toTest).doSecond("bye");
}
@Test
public void doSecondIsNotCalledWhenArgumentIsHello() {
toTest.doFirst("hello");
verify(toTest, never()).doSecond(anyString());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.