Reputation: 489
I am learning Mockito , i have trouble understanding few things. Suppose i want to test a Doa method which gets List of objects and saves it in DB by iterating ove the list . How do test it using Mockito. Below is the code example.
import java.util.Iterator;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
@Repository
public class AuditDaoImpl {
@PersistenceContext(unitName = "somepersistance")
EntityManager entityManager;
public <T> boolean saveAuditData(List<T> dataList) {
Iterator<Data> itr = (Iterator<Data>) dataList.iterator();
while (itr.hasNext()) {
Data Data = (Data) itr.next();
Audit audit = new Audit();
audit.setUserName(Data.getUserName());
entityManager.persist(audit);
}
return true;
}
}
Upvotes: 2
Views: 139
Reputation: 13509
Mockito is poor for testing cases that deal with the persistence layer. You should use an embedded container to test the persistance layer. An embedded container is an in memory database that simulates your Database and is fast to create, making it ideal for unit tests.
Look at this SO question and read the SECOND answer :
Upvotes: 0
Reputation: 2101
Assuming that your test class is annotated and running with spring (by using @RunWith(SpringJUnit4ClassRunner.class)
and @ContextConfiguration("classpath:applicationContext.xml")
) annotation and you have this working. And if your main concern is to verify that entityManager.persist(audit);
is invoked for each element, something like this should work
@Autowired //Autowired to get mockito to inject into the spring-handled dao
@InjectMocks
AuditDaoImpl auditDao;
@Mock
EntityManager entityManager;
@Test
public void saveAllAudit_entityManagerShouldPersistAll() {
List<Data> dataList = new ArrayList<>();
dataList.add(new Data("username"));
//add more to list
auditDao.saveAuditData(dataList);
verify(entityManager, times(1)).persist(anyObject());
}
If you actually need to test that it is persisted correctly, an in-memory database would be the way to go.
Upvotes: 2