Reputation: 47
I am working on creating integration test for a service class i am testing and I needed to mock the dao for one of the test methods. the problem is when i run the tests together some of my tests fail but when i run them individually the tests past. If i remove the mockito part all my tests pass when i run them all at once. any insight on this is appreciated
below is my code:
// here is my Service class
public class Service {
Dao dao;
public Dao getDao() {
return dao;
}
public void setDao(Dao dao) {
this.dao = dao;
}
}
//here is my integ test
@Category(IntegrationTest.class)
@RunWith(SpringRunner.class)
public class Test{
@Rule
public ExpectedException thrown = ExpectedException.none();
@Autowired
@Qualifier(Service.SERVICE_NAME)
protected Service service;
@Before
public void setUp() {
assertNotNull(service);
}
@Test
public void testDoSomethingOne() throws Exception {
Dao dao = Mockito(Dao.class)
service.setDao(dao)
boolean flag = service.doSomething();
Assert.assertTrue(flag);
}
@Test
public void testDoSomethingTwo() throws Exception {
Integer num = service.doSomething();
Assert.assertNotNull(num);
}
Upvotes: 0
Views: 1005
Reputation: 7121
The test method testDoSomethingOne()
sets the mock dao for the service instance which it retains for rest of the tests.
Annotate the method testDoSomethingOne()
with @DirtiesContext to get a fresh context associated with the subsequent test method.
Test annotation which indicates that the ApplicationContext associated with a test is dirty and should therefore be closed and removed from the context cache.
Use this annotation if a test has modified the context — for example, by modifying the state of a singleton bean, modifying the state of an embedded database, etc. Subsequent tests that request the same context will be supplied a new context.
Upvotes: 2
Reputation: 96
If it is a integration test you should not mock your daos, the recommended way is to use a in memory database like H2
. The spring folks already provide the annotation @DataJpaTest
that creates the database for you.
You can use the @DataJpaTest annotation to test JPA applications. By default, it scans for @Entity classes and configures Spring Data JPA repositories. If an embedded database is available on the classpath, it configures one as well. Regular @Component beans are not loaded into the ApplicationContext.
Upvotes: 0
Reputation: 4859
You can get the dao before each test and assign it back to service after the test something like this:
private static Dao dao;
@Before
public void setUp() {
if(dao == null) {
dao = service.getDao();
}
}
@After
public void tearDown() {
service.setDao(dao);
}
Upvotes: 0