在JMockit中删除先前定义的期望

chr*_*ney 6 unit-testing jmockit mocking

我有一个对象,我正在我的测试类NonStrictExcpection()@Before/ setUp()方法中使用JMockit进行模拟,以便它返回正常执行我的测试类所需的值.

这对我的所有测试方法都很好,除了我想要测试此代码的非正常操作的单个测试.

我已经尝试在测试方法中创建一个新的期望,我认为它会覆盖setUp方法中的期望,但我发现setUp方法中的期望抑制了新的期望.

当我删除setUp期望时,测试方法的行为与预期一致(但我所有其他测试自然都失败了).

我应该如何对我的测试类进行编码,以便能够以最少的代码量为每个测试正确定义期望值?(我知道我可以将期望代码复制/粘贴到每个测试方法中,如果完全可以避免,我不想这样做).

我的测试代码看起来像这样(注意,这是sorta伪代码并且不能编译,但你明白了):

public class TestClass{

    @Before
    public void setUp(){

        // Here I define the normal behaviour of mockObject
        new NonStrictExpectations() {{
            mockObject.doSomething();
            result = "Everyting is OK!";
        }};

        // Other set up stuff...

    }

    // Other Tests...

    /**
     * This method tests that an error when calling 
     * mockObject.doSomething() is handled correctly.
     */
    @Test(expected=Exception.class)
    public void testMockObjectThrowsException(){

        // This Expectation is apparently ignored...
        new NonStrictExpectations() {{
            mockObject.doSomething();
            result = "Something is wrong!";
        }};

        // Rest of test method...

    }
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*een 6

我通常只是创建一个返回Expectations类型的私有方法:

private Expectations expectTheUnknown()
{
    return new NonStrictExpectations()
    {{
        ... expectations ...
    }};
}
Run Code Online (Sandbox Code Playgroud)

然后只需在需要精确期望的测试方法中调用该方法:

@Test public void testUknown()
{
    expectTheUnknown();
    ... here goes the test ...
}
Run Code Online (Sandbox Code Playgroud)