new MockUp<SomeClass>() {
@Mock
boolean getValue() {
return true;
}
};
我希望从getValue()返回一个不同的值,具体取决于测试用例。我怎么能这样做?
答案 0 :(得分:3)
要在不同的测试中使用相同的模拟类的不同行为,您需要在每个单独的测试中指定所需的行为。例如,在这种情况下:
public class MyTest
{
@Test public void testUsingAMockUp()
{
new MockUp<SomeClass>() { @Mock boolean getValue() { return true; } };
// Call code under test which then calls SomeClass#getValue().
}
@Test public void anotherTestUsingAMockUp()
{
new MockUp<SomeClass>() { @Mock boolean getValue() { return false; } };
// Call code under test which then calls SomeClass#getValue().
}
@Test public void testUsingExpectations(@NonStrict final SomeClass mock)
{
new Expectations() {{ mock.getValue(); result = true; }};
// Call code under test which then calls SomeClass#getValue().
}
@Test public void anotherTestUsingExpectations(
@NonStrict final SomeClass mock)
{
// Not really needed because 'false' is the default for a boolean:
new Expectations() {{ mock.getValue(); result = false; }};
// Call code under test which then calls SomeClass#getValue().
}
}
当然,您可以创建可重用的 MockUp
和Expectations
子类,但它们也会在每个需要特定行为的测试中实例化。