public class TestClass {
@Mock
private SomeObject someObject;
@InjectMocks
private SubjectOfTesting subject;
@Before
public void setupMock() {
when(someObject.doSomething(eq("Meh")).thenReturn("Boing");
when(someObject.doSomething(eq("Foo")).thenReturn("Bar");
when(someObject.doSomething(any()).thenReturn("?!"); // <-- This any()
}
@Test
public void testSomethings() {
subject.setArgument("Meh");
String result = subject.useSomeObject();
assertEquals("result is not equal", "Boing", result);
}
// Multiple tests with other arguments.
}
给定上面的类,我可以同时使用any()
吗?它会按我的预期执行,根据我在测试中提供的参数返回"Boing"
、"Bar"
或"?!"
?
编辑
测试了它:
@RunWith(MockitoJUnitRunner.class)
public class TempTest {
@Mock
private SomeObject someObject;
@InjectMocks
private Subject subject = new Subject();
@Before
public void setupMock() {
when(someObject.doSomething(eq("Meh"))).thenReturn("Boing");
when(someObject.doSomething(eq("Foo"))).thenReturn("Bar");
when(someObject.doSomething(any())).thenReturn("?!"); // <-- This any()
}
@Test
public void testSomethingsMeh() {
subject.setArgument("Meh");
String result = subject.useSomeObject();
assertEquals("result is not equal", "Boing", result);
}
@Test
public void testSomethingsFoo() {
subject.setArgument("Foo");
String result = subject.useSomeObject();
assertEquals("result is not equal", "Bar", result);
}
@Test
public void testSomethingsAny() {
subject.setArgument("Any");
String result = subject.useSomeObject();
assertEquals("result is not equal", "?!", result);
}
private interface SomeObject {
String doSomething(String argument);
}
private class Subject {
private SomeObject someObject;
private String argument;
public Subject() {
}
public void setSomeObject(final SomeObject someObject) {
this.someObject = someObject;
}
public String useSomeObject() {
return this.someObject.doSomething(this.argument);
}
public void setArgument(final String argument) {
this.argument = argument;
}
}
}
结果为(两次失败,另一次通过(:
org.junit.ComparisonFailure: result is not equal expected:<[Bar]> but was:<[?!]>
org.junit.ComparisonFailure: result is not equal expected:<[Boing]> but was:<[?!]>
有没有办法让这些测试通过?
最后一个when
将覆盖所有以前的。但是,如果您更改存根的顺序,则可以获得所需的结果。这将按您的预期工作。
when(someObject.doSomething(any()).thenReturn("?!");
when(someObject.doSomething(eq("Meh")).thenReturn("Boing");
when(someObject.doSomething(eq("Foo")).thenReturn("Bar");