Search code examples
javaspringhibernaterestjunit

To write Junit Test cases for spring based REST API


For Spring based Rest API, in order to write JUnit test cases, do I need an established database connection or can i have a mock database. Can I get some suggestions.

Technology Stack used si: Spring MVC, Hibernate


Solution

  • It depends on what you are testing. If you are testing the service layer, you should not establish actual connections to the database. Instead, you can mock up repository objects, using Mockito, for example. Here is an example of how to wire up mock Repository objects.

    If you want to test your data access logic, you might consider using an in-memory database like hsqldb and define it as a test data source in the test configuration.

    For more sophisticated, integration testing, you might want to connect to the actual database.