NonStrictExcpection()
我有一个对象,我在我的测试类的@Before
/方法中使用 JMockit 进行模拟,setUp()
以便它返回预期的值,以便正常执行我的测试类。
这对于我的所有测试方法都很好,除了我想测试此代码的非正常操作的单个测试。
我尝试在测试方法中创建一个新的期望,我认为它会覆盖 setUp 方法中的期望,但我发现 setUp 方法中的期望正在抑制新的期望。
当我删除 setUp 期望时,测试方法会按预期运行(但我所有的其他测试自然会失败)。
我应该如何编码我的测试类,以便我可以用最少的代码为每个测试正确定义期望?(我知道我可以将期望代码复制/粘贴到每个测试方法中,但如果可以避免的话,我不想这样做)。
我的测试代码看起来像这样(注意,这是一种伪代码,不能编译,但你明白了):
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...
}
}