Removing previously defined expectations in JMockit

I have an object that I mock JMockit NonStrictExcpection()in the @Before/ method of setUp()my test class so that it returns the value expected for the normal execution of my test class.

This is great for all of my test methods, with the exception of one test where I want to test the abnormal operation of this code.

I tried to create a new wait in the test method, which I thought would override the wait in the setUp method, but I found that the wait in the setUp method suppresses the new wait.

When I remove the wait for setUp, the test method behaves as expected (but all my other tests fail, naturally).

How can I encode my test class so that I can correctly determine the expectations for each test with a minimum amount of code? (I know that I could copy / paste the wait code into each test method, but I do not want to do this, if at all, can be avoided).

My test code looks something like this (note that this is sorta psuedocode and does not compile, but you get the idea):

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...

    }
}
+5
source share
2 answers

Usually I just make a private method that returns a type Expectations:

private Expectations expectTheUnknown()
{
    return new NonStrictExpectations()
    {{
        ... expectations ...
    }};
}

And then just call the method in the test methods that need to be exact wait:

@Test public void testUknown()
{
    expectTheUnknown();
    ... here goes the test ...
}
+5
source

MockUp . , , . tearDown MockUp, .

0

All Articles