简体   繁体   English

为基于Spring的REST API编写Junit测试用例

[英]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. 对于基于Spring的Rest API,为了编写JUnit测试用例,我需要建立的数据库连接还是我可以有一个模拟数据库。 Can I get some suggestions. 我可以得到一些建议吗?

Technology Stack used si: Spring MVC, Hibernate 使用的技术堆栈si:Spring MVC,Hibernate

Under your root-context.xml you may consider setting up different bean profiles. 在您的root-context.xml您可以考虑设置不同的bean配置文件。 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: 然后在您的JUnit测试下,您可以考虑在测试上方使用@Profile批注:

@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 或者,您可以在application.properties文件中设置spring.profiles.active环境属性,或者通过-Dspring.profiles.active=dev将其设置为应用程序服务器的启动配置。

For more information, you may read the Spring docs on Profiles . 有关更多信息,您可以阅读Profiles上Spring文档

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. 相反,您可以使用Mockito模拟存储库对象。 Here is an example of how to wire up mock Repository objects. 是有关如何连接模拟存储库对象的示例。

If you want to test you data access logic, you might consider using in memory database like hsqldb and define it as a test data source in test configuration. 如果要测试数据访问逻辑,则可以考虑在内存数据库中使用hsqldb这样的数据库,并将其定义为测试配置中的测试数据源。

For more sofisticated, integration testing, you might want to connect to the actual database 对于更复杂的集成测试,您可能需要连接到实际数据库

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM