0
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"
または"?!"
を返しますか? (他が通過する2つの故障、)でモックに複数のwhenを使用するとどうなりますか?
@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;
}
}
}
結果::とそれをテスト
EDIT
org.junit.ComparisonFailure: result is not equal expected:<[Bar]> but was:<[?!]>
org.junit.ComparisonFailure: result is not equal expected:<[Boing]> but was:<[?!]>
は、これらのテストに合格させる方法はありますか?
コードの記述やデバッグに問題がありますか? – Adi
まあ、いいえ...質問を作成することは、自分自身で答えを得ることと同じくらい多くの仕事でした*。それで質問を広げた。 – Timo