'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 1:[1]
Under your root-context.xml you may consider setting up different bean profiles. For example:
<beans profile="dev">
<bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://192.168.1.2:3306/mydb"/>
<property name="username" value="admin"/>
<property name="password" value="password"/>
<property name="initialSize" value="3"/>
</bean>
...
</beans>
...
<beans profile="prod">
<bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://192.168.1.3:3306/mydb"/>
<property name="username" value="admin"/>
<property name="password" value="password"/>
<property name="initialSize" value="3"/>
</bean>
...
</beans>
And then under your JUnit tests you may consider using the @Profile annotation above your tests:
@Profile(value="dev")
Alternatively, you may set the spring.profiles.active environment property in your application.properties file or as a launch configuration for your application server via -Dspring.profiles.active=dev
For more information, you may read the Spring docs on Profiles.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | David Yee |
