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?
Aucun commentaire:
Enregistrer un commentaire