如何使用JUnit在Spring中获取数据库连接?

前端之家收集整理的这篇文章主要介绍了如何使用JUnit在Spring中获取数据库连接?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用服务和方法的正确逻辑来测试DB提供的正确信息.在这个简单的例子中,我只使用语句assertEquals来比较为roleService提供的id,但我仍然遇到错误.我有以下代码

[更新]

测试方法

  1. @RunWith(SpringJUnit4ClassRunner.class)
  2. @ContextConfiguration(value = { "classpath:applicationContext.xml" })
  3. @Transactional
  4. @WebAppConfiguration
  5. @ComponentScan(basePackages ={ "com.project.surveyengine" },excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,value = Configuration.class),@ComponentScan.Filter(type = FilterType.ANNOTATION,value = WebConfig.class)})
  6. public class RoleServiceTest {
  7.  
  8. @Configuration
  9. static class ContextConfiguration {
  10. @Bean
  11. public RoleService roleService() {
  12. RoleService roleService = new RoleService();
  13. // set properties,etc.
  14. return roleService;
  15. }
  16. }
  17.  
  18. private final LocalServiceTestHelper helper =
  19. new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig()
  20. .setDefaultHighRepJobPolicyUnappliedJobPercentage(100));
  21.  
  22. private Closeable closeable;
  23.  
  24. @Before
  25. public void setUp() {
  26. helper.setUp();
  27. ObjectifyService.register(Role.class);
  28. closeable = ObjectifyService.begin();
  29. }
  30.  
  31. @After
  32. public void tearDown() {
  33. closeable.close();
  34. helper.tearDown();
  35. }
  36.  
  37. @Autowired
  38. private RoleService roleService;
  39.  
  40. @Test
  41. public void existsRole() throws Exception{
  42. Role role = roleService.getByName("ROLE_ADMIN");
  43. assertEquals("Correct test",Long.valueOf("5067160539889664"),role.getId());
  44. }
  45.  
  46. }

RoleService是使用Google App Engine中的objectifyService查询数据库信息的服务类.

applicationContext.xml中

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
  6.  
  7. <context:annotation-config />
  8.  
  9. <context:component-scan base-package="com.project.surveyengine.config"/>
  10.  
  11. <!--Controllers-->
  12. <bean id="inBoxController" class="com.project.surveyengine.controller.InBoxController" autowire="byType"></bean>
  13. <bean id="mailController" class="com.project.surveyengine.controller.MailController" autowire="byType"></bean>
  14. <bean id="loginController" class="com.project.surveyengine.controller.LoginController" autowire="byType"></bean>
  15. <bean id="initController" class="com.project.surveyengine.controller.InitController" autowire="byType"></bean>
  16.  
  17. <!--Services-->
  18. <bean id="answerService" class="com.project.surveyengine.service.impl.AnswerService" autowire="byType"></bean>
  19. <bean id="blobService" class="com.project.surveyengine.service.impl.BlobService" autowire="byType"></bean>
  20. <bean id="mailService" class="com.project.surveyengine.service.impl.MailService" autowire="byType"></bean>
  21. <bean id="caseService" class="com.project.surveyengine.service.impl.CaseService" autowire="byType"></bean>
  22. <bean id="roleService" class="com.project.surveyengine.service.impl.RoleService" autowire="byType"></bean>
  23. </beans>

进入com.project.surveyengine.config我有以下三个类:

1)

  1. public class MyXmlWebApplicationContext extends XmlWebApplicationContext {
  2. protected void initBeanDefinitionReader(XmlBeanDefinitionReader beanDefinitionReader) {
  3. super.initBeanDefinitionReader(beanDefinitionReader);
  4. if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Production) {
  5. beanDefinitionReader.setValidating(false);
  6. beanDefinitionReader.setNamespaceAware(true);
  7. }
  8. }
  9. }

2)

  1. @Configuration
  2. @EnableWebMvc
  3. public class WebConfig extends WebMvcConfigurerAdapter{
  4. @Bean
  5. UrlBasedViewResolver resolver(){
  6. UrlBasedViewResolver resolver = new UrlBasedViewResolver();
  7. resolver.setPrefix("/views/");
  8. resolver.setSuffix(".jsp");
  9. resolver.setViewClass(JstlView.class);
  10. return resolver;
  11. }
  12.  
  13. @Override
  14. public void addResourceHandlers(ResourceHandlerRegistry registry) {
  15. registry.addResourceHandler("/statics/**").addResourceLocations("/statics/");
  16. }
  17. }

3)

  1. @Configuration
  2. @EnableWebSecurity
  3. @EnableGlobalMethodSecurity(prePostEnabled = true)
  4. public class SecurityContext extends WebSecurityConfigurerAdapter {
  5. @Override
  6. public void configure(WebSecurity web) throws Exception {
  7. web.ignoring().antMatchers("/statics/**");
  8. }
  9.  
  10. @Override
  11. protected void configure(HttpSecurity http) throws Exception {
  12. http
  13. .formLogin()
  14. //...more code
  15. }
  16. }

I’m getting this errors:

Dec 20,2016 4:40:03 PM
com.google.appengine.api.datastore.dev.LocalDatastoreService init
INFO: Local Datastore initialized: Type: High Replication Storage:
In-memory

java.lang.NullPointerException at
com.project.surveyengine.service.impl.RoleServiceTest.existsRole(RoleServiceTest.java:111)

  1. RoleServiceTest.java:111 = assertEquals("Correct test",role.getId());

解决方法

您是否尝试按照文档 http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/context/web/WebAppConfiguration.html中的建议添加@WebAppConfiguration?

我会用这种方式来测试你的测试代码

  1. @RunWith(SpringJUnit4ClassRunner.class)
  2. @ContextConfiguration(value = { "classpath:applicationContext.xml" })
  3. @TransactionConfiguration(transactionManager="txMgr",defaultRollback=false)
  4. @Transactional
  5. @WebAppConfiguration
  6. @ComponentScan(basePackages ={ "com.project.surveyengine" },excludeFilters = {
  7. @ComponentScan.Filter(type = FilterType.ANNOTATION,value = Configuration.class) })
  8. public class RoleServiceTest {
  9.  
  10. @Autowired
  11. private RoleService roleService;
  12.  
  13. @Test
  14. public void existsRole() throws Exception{
  15. Role role = roleService.getByName("ROLE_ADMIN");
  16. assertEquals("Correct test",role.getId());
  17. }
  18.  
  19. }

正如你所看到的,我也添加了注释@WebAppConfiguration

我希望这可以帮到你

猜你在找的Java相关文章