【问题标题】:How do I return multiple values from mocked method for different cases?对于不同的情况,如何从模拟方法返回多个值?
【发布时间】:2013-04-26 01:38:18
【问题描述】:
    new MockUp<SomeClass>() {
        @Mock
        boolean getValue() {
            return true;
        }
    };

我想根据测试用例从 getValue() 返回不同的值。我该怎么做?

【问题讨论】:

  • 为每个测试用例制作新的模型或期望是否有问题?
  • 您是否考虑过使用结果委托? jmockit.googlecode.com/svn/trunk/www/tutorial/…
  • 我不确定如何在同一个类上制作同一方法的多个模型。它只会执行第一个 MockUp。
  • 您能否举例说明您的问题?
  • getValue 是我的测试单元中的一个依赖项 - 它是包含被测单元的类中的公共方法。我有两个测试用例 - 一个需要该依赖项返回 true,另一个需要它返回 false。

标签: java unit-testing junit jmockit


【解决方案1】:

要在不同的测试中从同一个模拟类中获得不同的行为,您需要在 每个 单独的测试中指定所需的行为。例如,在这种情况下:

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().
    }
}

您当然可以创建可重用 MockUpExpectations 子类,但它们也将在需要特定行为的每个测试中实例化。

【讨论】:

  • 这是我之前尝试过的,但在第二种情况下它从未执行过模型。我想这是因为我忘记了我在测试班的另一个地方对整个班级的模拟。
猜你喜欢
  • 2016-01-30
  • 1970-01-01
  • 1970-01-01
  • 2022-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多