Testing Hibernate DAO methods with mockito2019 Community Moderator ElectionHow do you assert that a certain exception is thrown in JUnit 4 tests?What are the possible values of the #Hibernate hbm2ddl.auto configuration and what do they doHow to make mock to void methods with mockitohow to select value from database using hibernate?What's the difference between JPA and Hibernate?Writing a new dao. No Hibernate Session bound to threadH2 DB — Hibernate Example — Could not parse mapping document from resourceMockito test a void method throws an exceptionHibernate: ManyToMany inverse DeleteHibernate Transaction is not getting created in JUNIT tests
How to get the n-th line after a grepped one?
What does "^L" mean in C?
Print a physical multiplication table
Brake pads destroying wheels
Do I need to be arrogant to get ahead?
Do native speakers use "ultima" and "proxima" frequently in spoken English?
Unfrosted light bulb
A Ri-diddley-iley Riddle
Is there a hypothetical scenario that would make Earth uninhabitable for humans, but not for (the majority of) other animals?
Violin - Can double stops be played when the strings are not next to each other?
What does Jesus mean regarding "Raca," and "you fool?" - is he contrasting them?
Writing in a Christian voice
Generic TVP tradeoffs?
PTIJ What is the inyan of the Konami code in Uncle Moishy's song?
Why are there no stars visible in cislunar space?
Practical application of matrices and determinants
Knife as defense against stray dogs
What is the significance behind "40 days" that often appears in the Bible?
I got the following comment from a reputed math journal. What does it mean?
Help prove this basic trig identity please!
Are dual Irish/British citizens bound by the 90/180 day rule when travelling in the EU after Brexit?
Calculate the frequency of characters in a string
In Aliens, how many people were on LV-426 before the Marines arrived?
gerund and noun applications
Testing Hibernate DAO methods with mockito
2019 Community Moderator ElectionHow do you assert that a certain exception is thrown in JUnit 4 tests?What are the possible values of the #Hibernate hbm2ddl.auto configuration and what do they doHow to make mock to void methods with mockitohow to select value from database using hibernate?What's the difference between JPA and Hibernate?Writing a new dao. No Hibernate Session bound to threadH2 DB — Hibernate Example — Could not parse mapping document from resourceMockito test a void method throws an exceptionHibernate: ManyToMany inverse DeleteHibernate Transaction is not getting created in JUNIT tests
I have visited a lot of blogs and websites to learn how I can test my DAO methods in Hibernate with Mockito, but I haven't found any specific example that could help me with my code. All I have found is that I have to use Integration test instead of JUnit test but I don't really know how to do that with my code.
QUESTION: How can I test my DAO methods as good as possible?
MY CODE:
My test with only the mockito part:
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class UserDAOTest
@Mock
private UserDAO userDAO;
@Before
public void setUp()
MockitoAnnotations.initMocks(this);
@Test
public void testAddUser_AddsNewUser()
@Test
public void testDeleteUser_DeletesUser()
@Test
public void testGetUser_FetchUser()
@Test
public void testGetUsers_FetchesAllUsers()
My UserDAO:
import Hibernate.HibernateUtil;
import Hibernate.Models.User;
import org.hibernate.HibernateException;
import org.springframework.stereotype.Repository;
import org.hibernate.Session;
import org.hibernate.Transaction;
import java.util.List;
//@Transactional
@Repository
public class UserDAO extends GeneralDAO
public void addUser(User user)
add(user);
/**
* Deletes a user from the database based on the userID
* @param userID
*/
public void deleteUser(int userID)
User user = new User();
delete(userID, user);
public User getUser(int userID) throws Exception
Transaction transaction = null;
User user = null;
try (Session session = HibernateUtil.getSessionFactory().openSession())
// start a transaction
transaction = session.beginTransaction();
// Gets the user object
user = session.get(User.class, userID);
// commit transaction
transaction.commit();
//closing session
session.close();
return user;
catch (Exception e)
if (transaction != null)
transaction.rollback();
e.printStackTrace();
return user;
public List<User> getUsers() throws HibernateException, Exception
try(Session session = HibernateUtil.getSessionFactory().openSession())
return session.createQuery("FROM User", User.class).getResultList();
My GeneralDAO:
import Hibernate.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;
//@Transactional
@Repository
public class GeneralDAO
public void add(Object obj)
Transaction transaction = null;
try (Session session = HibernateUtil.getSessionFactory().openSession())
// start a transaction
transaction = session.beginTransaction();
// add the user object
session.save(obj);
// commit transaction
transaction.commit();
//closing session
session.close();
catch (Exception e)
if (transaction != null)
transaction.rollback();
e.printStackTrace();
public void delete(int userID, Object obj)
Transaction transaction = null;
try (Session session = HibernateUtil.getSessionFactory().openSession())
obj = session.load(obj.getClass(), userID);
// start a transaction
transaction = session.beginTransaction();
//deleting the user from the db
session.delete(obj);
// commit transaction
transaction.commit();
//closing session
session.close();
catch (Exception e)
if (transaction != null)
transaction.rollback();
e.printStackTrace();
java spring hibernate get
add a comment |
I have visited a lot of blogs and websites to learn how I can test my DAO methods in Hibernate with Mockito, but I haven't found any specific example that could help me with my code. All I have found is that I have to use Integration test instead of JUnit test but I don't really know how to do that with my code.
QUESTION: How can I test my DAO methods as good as possible?
MY CODE:
My test with only the mockito part:
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class UserDAOTest
@Mock
private UserDAO userDAO;
@Before
public void setUp()
MockitoAnnotations.initMocks(this);
@Test
public void testAddUser_AddsNewUser()
@Test
public void testDeleteUser_DeletesUser()
@Test
public void testGetUser_FetchUser()
@Test
public void testGetUsers_FetchesAllUsers()
My UserDAO:
import Hibernate.HibernateUtil;
import Hibernate.Models.User;
import org.hibernate.HibernateException;
import org.springframework.stereotype.Repository;
import org.hibernate.Session;
import org.hibernate.Transaction;
import java.util.List;
//@Transactional
@Repository
public class UserDAO extends GeneralDAO
public void addUser(User user)
add(user);
/**
* Deletes a user from the database based on the userID
* @param userID
*/
public void deleteUser(int userID)
User user = new User();
delete(userID, user);
public User getUser(int userID) throws Exception
Transaction transaction = null;
User user = null;
try (Session session = HibernateUtil.getSessionFactory().openSession())
// start a transaction
transaction = session.beginTransaction();
// Gets the user object
user = session.get(User.class, userID);
// commit transaction
transaction.commit();
//closing session
session.close();
return user;
catch (Exception e)
if (transaction != null)
transaction.rollback();
e.printStackTrace();
return user;
public List<User> getUsers() throws HibernateException, Exception
try(Session session = HibernateUtil.getSessionFactory().openSession())
return session.createQuery("FROM User", User.class).getResultList();
My GeneralDAO:
import Hibernate.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;
//@Transactional
@Repository
public class GeneralDAO
public void add(Object obj)
Transaction transaction = null;
try (Session session = HibernateUtil.getSessionFactory().openSession())
// start a transaction
transaction = session.beginTransaction();
// add the user object
session.save(obj);
// commit transaction
transaction.commit();
//closing session
session.close();
catch (Exception e)
if (transaction != null)
transaction.rollback();
e.printStackTrace();
public void delete(int userID, Object obj)
Transaction transaction = null;
try (Session session = HibernateUtil.getSessionFactory().openSession())
obj = session.load(obj.getClass(), userID);
// start a transaction
transaction = session.beginTransaction();
//deleting the user from the db
session.delete(obj);
// commit transaction
transaction.commit();
//closing session
session.close();
catch (Exception e)
if (transaction != null)
transaction.rollback();
e.printStackTrace();
java spring hibernate get
Is there a specific reason you're hand-writing DAOs instead of using Spring Data JpaRepository to do it all for you automatically?
– chrylis
Mar 7 at 18:09
But when I do it with JpaRepository, is it then simpeler to test the Service class where I then am going to use the CRUD operation in? I also saw 2 variations: CrudRepository and JpaRepository. What are the difference between the 2. In addition, how would you go about testing the CRUD operations then?
– MoNigma
Mar 7 at 19:29
(2) You don't test framework code, generally--you trust the Spring Data developers to have tested it and for it to work. (1) You can read the docs on the specifics, but JpaRepository is more specific particularly for when you are using multiple Spring Data backends (e.g., JPA and MongoDB) and need to be explicit about where to route queries. (And the repository abstraction makes testing drastically easier because you can just mock the repository directly.)
– chrylis
Mar 7 at 20:44
add a comment |
I have visited a lot of blogs and websites to learn how I can test my DAO methods in Hibernate with Mockito, but I haven't found any specific example that could help me with my code. All I have found is that I have to use Integration test instead of JUnit test but I don't really know how to do that with my code.
QUESTION: How can I test my DAO methods as good as possible?
MY CODE:
My test with only the mockito part:
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class UserDAOTest
@Mock
private UserDAO userDAO;
@Before
public void setUp()
MockitoAnnotations.initMocks(this);
@Test
public void testAddUser_AddsNewUser()
@Test
public void testDeleteUser_DeletesUser()
@Test
public void testGetUser_FetchUser()
@Test
public void testGetUsers_FetchesAllUsers()
My UserDAO:
import Hibernate.HibernateUtil;
import Hibernate.Models.User;
import org.hibernate.HibernateException;
import org.springframework.stereotype.Repository;
import org.hibernate.Session;
import org.hibernate.Transaction;
import java.util.List;
//@Transactional
@Repository
public class UserDAO extends GeneralDAO
public void addUser(User user)
add(user);
/**
* Deletes a user from the database based on the userID
* @param userID
*/
public void deleteUser(int userID)
User user = new User();
delete(userID, user);
public User getUser(int userID) throws Exception
Transaction transaction = null;
User user = null;
try (Session session = HibernateUtil.getSessionFactory().openSession())
// start a transaction
transaction = session.beginTransaction();
// Gets the user object
user = session.get(User.class, userID);
// commit transaction
transaction.commit();
//closing session
session.close();
return user;
catch (Exception e)
if (transaction != null)
transaction.rollback();
e.printStackTrace();
return user;
public List<User> getUsers() throws HibernateException, Exception
try(Session session = HibernateUtil.getSessionFactory().openSession())
return session.createQuery("FROM User", User.class).getResultList();
My GeneralDAO:
import Hibernate.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;
//@Transactional
@Repository
public class GeneralDAO
public void add(Object obj)
Transaction transaction = null;
try (Session session = HibernateUtil.getSessionFactory().openSession())
// start a transaction
transaction = session.beginTransaction();
// add the user object
session.save(obj);
// commit transaction
transaction.commit();
//closing session
session.close();
catch (Exception e)
if (transaction != null)
transaction.rollback();
e.printStackTrace();
public void delete(int userID, Object obj)
Transaction transaction = null;
try (Session session = HibernateUtil.getSessionFactory().openSession())
obj = session.load(obj.getClass(), userID);
// start a transaction
transaction = session.beginTransaction();
//deleting the user from the db
session.delete(obj);
// commit transaction
transaction.commit();
//closing session
session.close();
catch (Exception e)
if (transaction != null)
transaction.rollback();
e.printStackTrace();
java spring hibernate get
I have visited a lot of blogs and websites to learn how I can test my DAO methods in Hibernate with Mockito, but I haven't found any specific example that could help me with my code. All I have found is that I have to use Integration test instead of JUnit test but I don't really know how to do that with my code.
QUESTION: How can I test my DAO methods as good as possible?
MY CODE:
My test with only the mockito part:
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class UserDAOTest
@Mock
private UserDAO userDAO;
@Before
public void setUp()
MockitoAnnotations.initMocks(this);
@Test
public void testAddUser_AddsNewUser()
@Test
public void testDeleteUser_DeletesUser()
@Test
public void testGetUser_FetchUser()
@Test
public void testGetUsers_FetchesAllUsers()
My UserDAO:
import Hibernate.HibernateUtil;
import Hibernate.Models.User;
import org.hibernate.HibernateException;
import org.springframework.stereotype.Repository;
import org.hibernate.Session;
import org.hibernate.Transaction;
import java.util.List;
//@Transactional
@Repository
public class UserDAO extends GeneralDAO
public void addUser(User user)
add(user);
/**
* Deletes a user from the database based on the userID
* @param userID
*/
public void deleteUser(int userID)
User user = new User();
delete(userID, user);
public User getUser(int userID) throws Exception
Transaction transaction = null;
User user = null;
try (Session session = HibernateUtil.getSessionFactory().openSession())
// start a transaction
transaction = session.beginTransaction();
// Gets the user object
user = session.get(User.class, userID);
// commit transaction
transaction.commit();
//closing session
session.close();
return user;
catch (Exception e)
if (transaction != null)
transaction.rollback();
e.printStackTrace();
return user;
public List<User> getUsers() throws HibernateException, Exception
try(Session session = HibernateUtil.getSessionFactory().openSession())
return session.createQuery("FROM User", User.class).getResultList();
My GeneralDAO:
import Hibernate.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Repository;
//@Transactional
@Repository
public class GeneralDAO
public void add(Object obj)
Transaction transaction = null;
try (Session session = HibernateUtil.getSessionFactory().openSession())
// start a transaction
transaction = session.beginTransaction();
// add the user object
session.save(obj);
// commit transaction
transaction.commit();
//closing session
session.close();
catch (Exception e)
if (transaction != null)
transaction.rollback();
e.printStackTrace();
public void delete(int userID, Object obj)
Transaction transaction = null;
try (Session session = HibernateUtil.getSessionFactory().openSession())
obj = session.load(obj.getClass(), userID);
// start a transaction
transaction = session.beginTransaction();
//deleting the user from the db
session.delete(obj);
// commit transaction
transaction.commit();
//closing session
session.close();
catch (Exception e)
if (transaction != null)
transaction.rollback();
e.printStackTrace();
java spring hibernate get
java spring hibernate get
asked Mar 7 at 17:31
MoNigmaMoNigma
398
398
Is there a specific reason you're hand-writing DAOs instead of using Spring Data JpaRepository to do it all for you automatically?
– chrylis
Mar 7 at 18:09
But when I do it with JpaRepository, is it then simpeler to test the Service class where I then am going to use the CRUD operation in? I also saw 2 variations: CrudRepository and JpaRepository. What are the difference between the 2. In addition, how would you go about testing the CRUD operations then?
– MoNigma
Mar 7 at 19:29
(2) You don't test framework code, generally--you trust the Spring Data developers to have tested it and for it to work. (1) You can read the docs on the specifics, but JpaRepository is more specific particularly for when you are using multiple Spring Data backends (e.g., JPA and MongoDB) and need to be explicit about where to route queries. (And the repository abstraction makes testing drastically easier because you can just mock the repository directly.)
– chrylis
Mar 7 at 20:44
add a comment |
Is there a specific reason you're hand-writing DAOs instead of using Spring Data JpaRepository to do it all for you automatically?
– chrylis
Mar 7 at 18:09
But when I do it with JpaRepository, is it then simpeler to test the Service class where I then am going to use the CRUD operation in? I also saw 2 variations: CrudRepository and JpaRepository. What are the difference between the 2. In addition, how would you go about testing the CRUD operations then?
– MoNigma
Mar 7 at 19:29
(2) You don't test framework code, generally--you trust the Spring Data developers to have tested it and for it to work. (1) You can read the docs on the specifics, but JpaRepository is more specific particularly for when you are using multiple Spring Data backends (e.g., JPA and MongoDB) and need to be explicit about where to route queries. (And the repository abstraction makes testing drastically easier because you can just mock the repository directly.)
– chrylis
Mar 7 at 20:44
Is there a specific reason you're hand-writing DAOs instead of using Spring Data JpaRepository to do it all for you automatically?
– chrylis
Mar 7 at 18:09
Is there a specific reason you're hand-writing DAOs instead of using Spring Data JpaRepository to do it all for you automatically?
– chrylis
Mar 7 at 18:09
But when I do it with JpaRepository, is it then simpeler to test the Service class where I then am going to use the CRUD operation in? I also saw 2 variations: CrudRepository and JpaRepository. What are the difference between the 2. In addition, how would you go about testing the CRUD operations then?
– MoNigma
Mar 7 at 19:29
But when I do it with JpaRepository, is it then simpeler to test the Service class where I then am going to use the CRUD operation in? I also saw 2 variations: CrudRepository and JpaRepository. What are the difference between the 2. In addition, how would you go about testing the CRUD operations then?
– MoNigma
Mar 7 at 19:29
(2) You don't test framework code, generally--you trust the Spring Data developers to have tested it and for it to work. (1) You can read the docs on the specifics, but JpaRepository is more specific particularly for when you are using multiple Spring Data backends (e.g., JPA and MongoDB) and need to be explicit about where to route queries. (And the repository abstraction makes testing drastically easier because you can just mock the repository directly.)
– chrylis
Mar 7 at 20:44
(2) You don't test framework code, generally--you trust the Spring Data developers to have tested it and for it to work. (1) You can read the docs on the specifics, but JpaRepository is more specific particularly for when you are using multiple Spring Data backends (e.g., JPA and MongoDB) and need to be explicit about where to route queries. (And the repository abstraction makes testing drastically easier because you can just mock the repository directly.)
– chrylis
Mar 7 at 20:44
add a comment |
1 Answer
1
active
oldest
votes
What you read about testing DAO is the correct way.
Don' test with Mockito the DAO/repository layer.
You don't want to write an unit test that asserts that a flow of statements was indeed invoked :
// start a transaction
transaction = session.beginTransaction();
// add the user object
session.save(obj);
// commit transaction
transaction.commit();
//closing session
session.close();
Writing this kind of test means writing mainly mock to describe the flow.
No value because it checks nothings in terms of logical/behavior.
Similarly, asserting a query is useless. You could write "SELECT SELECT SELECT" as query in your DAO and your test could still success if you rely on checking query text.
You use Spring. If you also use Spring Boot, you should rely on the @DataJpaTest
test slicing that focuses on testing the data access components.
Otherwise, don't worry. We did it before Spring Boot. So we could still do it.
Configure an in memory database (H2 for example) for your test, and clear/populate data according to the tested method.
For example :
@Autowired
UserDAO userDAO;
@Test
public void getUser_retrieves_users_added_by_addUser()
User addedUser = userDAO.add(new User("foo", "bar"));
// ... flush data in the database and clear first cache level to avoid cache using
User expectedUser = userDAO.get(addedUser.getId());
// assert the expected User
@Before
public void tearDown()
// clear data in the database
Hey David, thanks for your quick response. I have also thought about doing it like that but I already have a database that I host, so is there any method of testing my DAOs using the original database with combination of rollback functionality somehow? Instead of using a new database. Also can you clarify what you mean by in-memory database? Is it just a database that I have to run my tests on separately (so as a localhost database) instead of using my original database? And do I also have to make a new hibernate.cfg.xml file for it because mine is now connected with my hosted database.
– MoNigma
Mar 7 at 18:53
Hello Tom, you are welcome. Generally you don't want to use the applicative/"original" database because you don't want to pollute it with some data. Besides the application and the test could read/modifying data in a concurrent way, it will make test not reproducible and your application inconsistent : you don't want that. A in memory database is a large matter but yes you summarize it quite well. You can see it some examples with Spring here dzone.com/articles/… and here baeldung.com/spring-testing-separate-data-source
– davidxxx
Mar 7 at 20:13
Ok thanks for the suggestions to setup an In-memory db, these make testing much easier :) .
– MoNigma
Mar 8 at 12:44
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55049744%2ftesting-hibernate-dao-methods-with-mockito%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
What you read about testing DAO is the correct way.
Don' test with Mockito the DAO/repository layer.
You don't want to write an unit test that asserts that a flow of statements was indeed invoked :
// start a transaction
transaction = session.beginTransaction();
// add the user object
session.save(obj);
// commit transaction
transaction.commit();
//closing session
session.close();
Writing this kind of test means writing mainly mock to describe the flow.
No value because it checks nothings in terms of logical/behavior.
Similarly, asserting a query is useless. You could write "SELECT SELECT SELECT" as query in your DAO and your test could still success if you rely on checking query text.
You use Spring. If you also use Spring Boot, you should rely on the @DataJpaTest
test slicing that focuses on testing the data access components.
Otherwise, don't worry. We did it before Spring Boot. So we could still do it.
Configure an in memory database (H2 for example) for your test, and clear/populate data according to the tested method.
For example :
@Autowired
UserDAO userDAO;
@Test
public void getUser_retrieves_users_added_by_addUser()
User addedUser = userDAO.add(new User("foo", "bar"));
// ... flush data in the database and clear first cache level to avoid cache using
User expectedUser = userDAO.get(addedUser.getId());
// assert the expected User
@Before
public void tearDown()
// clear data in the database
Hey David, thanks for your quick response. I have also thought about doing it like that but I already have a database that I host, so is there any method of testing my DAOs using the original database with combination of rollback functionality somehow? Instead of using a new database. Also can you clarify what you mean by in-memory database? Is it just a database that I have to run my tests on separately (so as a localhost database) instead of using my original database? And do I also have to make a new hibernate.cfg.xml file for it because mine is now connected with my hosted database.
– MoNigma
Mar 7 at 18:53
Hello Tom, you are welcome. Generally you don't want to use the applicative/"original" database because you don't want to pollute it with some data. Besides the application and the test could read/modifying data in a concurrent way, it will make test not reproducible and your application inconsistent : you don't want that. A in memory database is a large matter but yes you summarize it quite well. You can see it some examples with Spring here dzone.com/articles/… and here baeldung.com/spring-testing-separate-data-source
– davidxxx
Mar 7 at 20:13
Ok thanks for the suggestions to setup an In-memory db, these make testing much easier :) .
– MoNigma
Mar 8 at 12:44
add a comment |
What you read about testing DAO is the correct way.
Don' test with Mockito the DAO/repository layer.
You don't want to write an unit test that asserts that a flow of statements was indeed invoked :
// start a transaction
transaction = session.beginTransaction();
// add the user object
session.save(obj);
// commit transaction
transaction.commit();
//closing session
session.close();
Writing this kind of test means writing mainly mock to describe the flow.
No value because it checks nothings in terms of logical/behavior.
Similarly, asserting a query is useless. You could write "SELECT SELECT SELECT" as query in your DAO and your test could still success if you rely on checking query text.
You use Spring. If you also use Spring Boot, you should rely on the @DataJpaTest
test slicing that focuses on testing the data access components.
Otherwise, don't worry. We did it before Spring Boot. So we could still do it.
Configure an in memory database (H2 for example) for your test, and clear/populate data according to the tested method.
For example :
@Autowired
UserDAO userDAO;
@Test
public void getUser_retrieves_users_added_by_addUser()
User addedUser = userDAO.add(new User("foo", "bar"));
// ... flush data in the database and clear first cache level to avoid cache using
User expectedUser = userDAO.get(addedUser.getId());
// assert the expected User
@Before
public void tearDown()
// clear data in the database
Hey David, thanks for your quick response. I have also thought about doing it like that but I already have a database that I host, so is there any method of testing my DAOs using the original database with combination of rollback functionality somehow? Instead of using a new database. Also can you clarify what you mean by in-memory database? Is it just a database that I have to run my tests on separately (so as a localhost database) instead of using my original database? And do I also have to make a new hibernate.cfg.xml file for it because mine is now connected with my hosted database.
– MoNigma
Mar 7 at 18:53
Hello Tom, you are welcome. Generally you don't want to use the applicative/"original" database because you don't want to pollute it with some data. Besides the application and the test could read/modifying data in a concurrent way, it will make test not reproducible and your application inconsistent : you don't want that. A in memory database is a large matter but yes you summarize it quite well. You can see it some examples with Spring here dzone.com/articles/… and here baeldung.com/spring-testing-separate-data-source
– davidxxx
Mar 7 at 20:13
Ok thanks for the suggestions to setup an In-memory db, these make testing much easier :) .
– MoNigma
Mar 8 at 12:44
add a comment |
What you read about testing DAO is the correct way.
Don' test with Mockito the DAO/repository layer.
You don't want to write an unit test that asserts that a flow of statements was indeed invoked :
// start a transaction
transaction = session.beginTransaction();
// add the user object
session.save(obj);
// commit transaction
transaction.commit();
//closing session
session.close();
Writing this kind of test means writing mainly mock to describe the flow.
No value because it checks nothings in terms of logical/behavior.
Similarly, asserting a query is useless. You could write "SELECT SELECT SELECT" as query in your DAO and your test could still success if you rely on checking query text.
You use Spring. If you also use Spring Boot, you should rely on the @DataJpaTest
test slicing that focuses on testing the data access components.
Otherwise, don't worry. We did it before Spring Boot. So we could still do it.
Configure an in memory database (H2 for example) for your test, and clear/populate data according to the tested method.
For example :
@Autowired
UserDAO userDAO;
@Test
public void getUser_retrieves_users_added_by_addUser()
User addedUser = userDAO.add(new User("foo", "bar"));
// ... flush data in the database and clear first cache level to avoid cache using
User expectedUser = userDAO.get(addedUser.getId());
// assert the expected User
@Before
public void tearDown()
// clear data in the database
What you read about testing DAO is the correct way.
Don' test with Mockito the DAO/repository layer.
You don't want to write an unit test that asserts that a flow of statements was indeed invoked :
// start a transaction
transaction = session.beginTransaction();
// add the user object
session.save(obj);
// commit transaction
transaction.commit();
//closing session
session.close();
Writing this kind of test means writing mainly mock to describe the flow.
No value because it checks nothings in terms of logical/behavior.
Similarly, asserting a query is useless. You could write "SELECT SELECT SELECT" as query in your DAO and your test could still success if you rely on checking query text.
You use Spring. If you also use Spring Boot, you should rely on the @DataJpaTest
test slicing that focuses on testing the data access components.
Otherwise, don't worry. We did it before Spring Boot. So we could still do it.
Configure an in memory database (H2 for example) for your test, and clear/populate data according to the tested method.
For example :
@Autowired
UserDAO userDAO;
@Test
public void getUser_retrieves_users_added_by_addUser()
User addedUser = userDAO.add(new User("foo", "bar"));
// ... flush data in the database and clear first cache level to avoid cache using
User expectedUser = userDAO.get(addedUser.getId());
// assert the expected User
@Before
public void tearDown()
// clear data in the database
answered Mar 7 at 17:51
davidxxxdavidxxx
68.4k67398
68.4k67398
Hey David, thanks for your quick response. I have also thought about doing it like that but I already have a database that I host, so is there any method of testing my DAOs using the original database with combination of rollback functionality somehow? Instead of using a new database. Also can you clarify what you mean by in-memory database? Is it just a database that I have to run my tests on separately (so as a localhost database) instead of using my original database? And do I also have to make a new hibernate.cfg.xml file for it because mine is now connected with my hosted database.
– MoNigma
Mar 7 at 18:53
Hello Tom, you are welcome. Generally you don't want to use the applicative/"original" database because you don't want to pollute it with some data. Besides the application and the test could read/modifying data in a concurrent way, it will make test not reproducible and your application inconsistent : you don't want that. A in memory database is a large matter but yes you summarize it quite well. You can see it some examples with Spring here dzone.com/articles/… and here baeldung.com/spring-testing-separate-data-source
– davidxxx
Mar 7 at 20:13
Ok thanks for the suggestions to setup an In-memory db, these make testing much easier :) .
– MoNigma
Mar 8 at 12:44
add a comment |
Hey David, thanks for your quick response. I have also thought about doing it like that but I already have a database that I host, so is there any method of testing my DAOs using the original database with combination of rollback functionality somehow? Instead of using a new database. Also can you clarify what you mean by in-memory database? Is it just a database that I have to run my tests on separately (so as a localhost database) instead of using my original database? And do I also have to make a new hibernate.cfg.xml file for it because mine is now connected with my hosted database.
– MoNigma
Mar 7 at 18:53
Hello Tom, you are welcome. Generally you don't want to use the applicative/"original" database because you don't want to pollute it with some data. Besides the application and the test could read/modifying data in a concurrent way, it will make test not reproducible and your application inconsistent : you don't want that. A in memory database is a large matter but yes you summarize it quite well. You can see it some examples with Spring here dzone.com/articles/… and here baeldung.com/spring-testing-separate-data-source
– davidxxx
Mar 7 at 20:13
Ok thanks for the suggestions to setup an In-memory db, these make testing much easier :) .
– MoNigma
Mar 8 at 12:44
Hey David, thanks for your quick response. I have also thought about doing it like that but I already have a database that I host, so is there any method of testing my DAOs using the original database with combination of rollback functionality somehow? Instead of using a new database. Also can you clarify what you mean by in-memory database? Is it just a database that I have to run my tests on separately (so as a localhost database) instead of using my original database? And do I also have to make a new hibernate.cfg.xml file for it because mine is now connected with my hosted database.
– MoNigma
Mar 7 at 18:53
Hey David, thanks for your quick response. I have also thought about doing it like that but I already have a database that I host, so is there any method of testing my DAOs using the original database with combination of rollback functionality somehow? Instead of using a new database. Also can you clarify what you mean by in-memory database? Is it just a database that I have to run my tests on separately (so as a localhost database) instead of using my original database? And do I also have to make a new hibernate.cfg.xml file for it because mine is now connected with my hosted database.
– MoNigma
Mar 7 at 18:53
Hello Tom, you are welcome. Generally you don't want to use the applicative/"original" database because you don't want to pollute it with some data. Besides the application and the test could read/modifying data in a concurrent way, it will make test not reproducible and your application inconsistent : you don't want that. A in memory database is a large matter but yes you summarize it quite well. You can see it some examples with Spring here dzone.com/articles/… and here baeldung.com/spring-testing-separate-data-source
– davidxxx
Mar 7 at 20:13
Hello Tom, you are welcome. Generally you don't want to use the applicative/"original" database because you don't want to pollute it with some data. Besides the application and the test could read/modifying data in a concurrent way, it will make test not reproducible and your application inconsistent : you don't want that. A in memory database is a large matter but yes you summarize it quite well. You can see it some examples with Spring here dzone.com/articles/… and here baeldung.com/spring-testing-separate-data-source
– davidxxx
Mar 7 at 20:13
Ok thanks for the suggestions to setup an In-memory db, these make testing much easier :) .
– MoNigma
Mar 8 at 12:44
Ok thanks for the suggestions to setup an In-memory db, these make testing much easier :) .
– MoNigma
Mar 8 at 12:44
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55049744%2ftesting-hibernate-dao-methods-with-mockito%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Is there a specific reason you're hand-writing DAOs instead of using Spring Data JpaRepository to do it all for you automatically?
– chrylis
Mar 7 at 18:09
But when I do it with JpaRepository, is it then simpeler to test the Service class where I then am going to use the CRUD operation in? I also saw 2 variations: CrudRepository and JpaRepository. What are the difference between the 2. In addition, how would you go about testing the CRUD operations then?
– MoNigma
Mar 7 at 19:29
(2) You don't test framework code, generally--you trust the Spring Data developers to have tested it and for it to work. (1) You can read the docs on the specifics, but JpaRepository is more specific particularly for when you are using multiple Spring Data backends (e.g., JPA and MongoDB) and need to be explicit about where to route queries. (And the repository abstraction makes testing drastically easier because you can just mock the repository directly.)
– chrylis
Mar 7 at 20:44