A JUnit rule designed to help with the automatic revert of test objects with mocked fields.
This is intended to be used when writing test code and you wish to set a mock object on a spring singleton bean.
By mocking out fields on spring singletons beans, if you don't remember to revert them to their original values, then
any subsequent tests that expect to see 'proper' services plugged in, may fail when they are instead given a mock.
Example usage:
public class YourTestClass
{
// Declare the rule.
@Rule public final TemporaryMockOverride mockOverride = new TemporaryMockOverride();
@Test public void aTestMethod()
{
// Get a singleton bean from the spring context
FooService fooService = appContext.getBean("fooService", FooService.class);
// Create a mocked service (this uses Mockito, but that's not required for this rule to work)
BarService mockedBarService = mock(BarService.class);
// Don't do this as you're just replacing the original barService: fooService.setBarService(mockedBarService);
// Instead do this:
mockOverride.setTemporaryField(fooService, barService, mockedBarService);
// Go ahead and use the FooService in test code, whilst relying on a mocked BarService behind it.
// After the rule has completed, the original BarService which spring injected into the FooService will be reset.
}
}