I have any issue in my unit test where I have something along the lines of this. The mock injection get overridden on the someService if the blargh
function is annotated with Transactional. If I remove the Transactional the mock stays there. From watching the code it appears that Spring lazily loads the services when a function in the service is annotated with transactinal, but eagerly loads the services when it isn't. This overrides the mock I injected.
Is there a better way to do this?
@Component
public class SomeTests
{
@Autowired
private SomeService someService;
@Test
@Transactional
public void test(){
FooBar fooBarMock = mock(FooBar.class);
ReflectionTestUtils.setField(someService, "fooBar", fooBarMock);
}
}
@Service
public class someService
{
@Autowired FooBar foobar;
@Transactional // <-- this causes the mocked item to be overridden
public void blargh()
{
fooBar.doStuff();
}
}