I have a simple service where I prepopulate a user db table with a default user. The service looks like this:
@Service
public class BootstrapService
{
@Autowired
UserRepository userRepository;
public void bootstrap()
{
User user = new User("admin", "password");
userRepository.save(user);
}
}
I call this service on application startup by using an ApplicationListener:
@Component
public class ApplicationStartup implements ApplicationListener<ApplicationReadyEvent>
{
@Autowired
private BootstrapService bootstrapService;
@Override
public void onApplicationEvent(final ApplicationReadyEvent event)
{
bootstrapService.bootstrap();
}
}
Now I want to write a unit test for the BootstrapService that checks if a user was really added, like this:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MyApplication.class)
@Transactional
public class BootstrapServiceTests
{
@Autowired
private UserRepository userRepository;
@Autowired
private BootstrapService bootstrapService;
@Test
public void testBootstrap()
{
bootstrapService.bootstrap();
assertEquals(1, userRepository.count());
}
}
However what happens is that the bootstrapService.bootstrap() function gets called twice - once by the ApplicationListener and once by the test itself, resulting in two users being added to the DB.
How can I prevent the ApplicationListener#ApplicationReadyEvent getting triggered while running the test?
As mentioned in comment, You can try to mock the listener (but I'm not sure if it will work in this precise case). Other way that I can think of (this works for sure) is to use Spring profiles, to exclude ApplicationStartup from running in test profile, like this:
@Component
@Profile("!test")
public class ApplicationStartup implements ApplicationListener<ApplicationReadyEvent>
Then when You run Your tests, simply use environment switch: --spring.profiles.active=test
The drawback is that ApplicationStartup will be excluded from every test run with "test" profile.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With