I'm trying to unit test a class (let's say, "ClassUnderTest") and its use of a particular library class (let's call it "Helper"). So I'm injecting a mocked Helper into the ClassUnderTest and using Expectations to check things out.
public class TestUseOfHelper {
@Autowired ClassUnderTest classUnderTest;
@Mocked HelperClass helper;
[...]
@Before
public void setUp() throws Exception {
Deencapsulation.setField(classUnderTest, "helper", helper);
}
[...]
@Test
public void test() {
new Expectations() {{
helper.doSomething(any);
}};
classUnderTest.useHelper();
}
So far, so good.
In other tests (same package, different file), I'm testing other aspects of the ClassUnderTest where I just want Helper to do its thing.
public class TestOtherQualities {
@Autowired ClassUnderTest classUnderTest;
[...]
@Test
public void test() {
result = classUnderTest.processSomething();
assertNonNull(result);
}
Those tests work fine as well.
The problem comes in when I run the suite of tests. Now, the second set fails, apparently because the Mocked Helper is still in place!
I assume that the full suite is being executed in the same JVM and that Spring has created one ClassUnderTest, injects the mock like it's told, but then just reuses the same ClassUnderTest object for the next test. How do I keep them separate? How can I get "fresh" objects for each separate test file? What am I not getting/googling?
I've tried numerous variations of defining objects within the Expectations blocks and using @Tested/@Injected but with no luck. BTW, I'm avoiding mocking the Helper in other tests because I need it to do its thing. Also ClassUnderTest autowires a bunch of other objects, which in turn autowire still others, so mocking everything that ClassUnderTest references is impractical.
Any insights, Oh knowledgeable Stack Overflow Magic 8 Ball? ("Try Later" is not acceptable.)
Annotate the test class with
@DirtiesContext(classMode = AFTER_CLASS)
if you want to reset the app context between test classes.