Removing previously defined expectations in JMockit
I have an object that I'm mocking with a JMockit NonStrictExcpection()
in the @Before
/setUp()
method of my test class so that it returns the value expected for normal execution of my class under test.
This is fine for all of my test methods save for a single test where I want to test non-normal operation of this code.
I have tried creating a new expectation in the test method, which I believed would override the expectation in the setUp method, but I have found that the expectation in the setUp method is suppressing the new expectation.
When I remove the setUp expectation, the test method behaves as expected (but all my other tests fail, naturally).
How should I code my test class so that I can have the expectations correctly defined for each test with the minimum amount of code? (I know I could copy/paste the expectation code into each test method, but I don't want to do that if at all avoidable).
My test code looks something like this (note, this is sorta psuedocode and doesn't compile, but you get the idea):
public class TestClass{
@Before
public void setUp(){
// Here I define the normal behaviour of mockO开发者_C百科bject
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...
}
}
I usually just make a private method which returns an Expectations
type:
private Expectations expectTheUnknown()
{
return new NonStrictExpectations()
{{
... expectations ...
}};
}
And then just call the method in the test methods that need the exact expectation:
@Test public void testUknown()
{
expectTheUnknown();
... here goes the test ...
}
You can better use MockUp for state based testing. Define the Mockup you want in each test method. You can call the tearDown method of MockUp to remove the mock at the end of each test.
It is described here
精彩评论