2
    new MockUp<SomeClass>() {
        @Mock
        boolean getValue() {
            return true;
        }
    };

我想根据测试用例从 getValue() 返回不同的值。我怎样才能做到这一点?

4

1 回答 1

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子类,但它们也将在需要特定行为的每个测试中实例化。

于 2013-05-02T12:41:13.803 回答