Reputation: 4940
Let's say we have a service layer :
@Service
public class MyServiceImpl implements MyService {
@Autowired
private MyDAO myDAO;
@Transactional
public void myMethod(SomeObject someObject) {
myDAO.insertIntoMyDb(someObject);
}
}
Let us say myDAO uses spring jdbc :
@Repository
public class MyDAOImpl implements MyDAO {
@Autowired
private NamedParameterJdbcTemplate jdbcTemplate;
@Override
public void insertIntoMyDb(SomeObject object) {
// some code before this where we get query and param
int numberOfRowsUpdated = jdbcTemplate.update(query,param);
if(numberOfRowsUpdated != 1)
throw new Exception("Error while inserting a record in database. Actual records inserted : " + numberOfRowsUpdated);
}
}
I want to write 2 tests.
The first test will check my dao layer only. I want to make a jdbc call here , get data and verify. I don't want to mock them.
The second test is integration test. I want my service layer to call Dao layer. Note that there is transaction. Now this will give me data from DAO. Again DAO has to connect to db to get data.
I am using spring boot. My database properties are present in applicationITest.properties file.
How to do these 2 testing ? What is the correct annotations I have to use ? Can some one provide an example ?
Upvotes: 1
Views: 1185
Reputation: 21381
a) Rollback will happen by default as long as you annotate your Test class with @Transactional
. Documentation about Test-managed transactions.
sample test class:
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = MyTestConfig.class)
@Transactional
public class MyClassTest {
//..
@Test
public void myTest() {
//..
}
//..
}
b) Yes you can enforce the commit using the @Commit (added in Spring 4.2) test annotation. Here's the documentation.
Upvotes: 2