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

我试图使用服务和方法的正确逻辑来测试从DB给出的正确信息。 在这个简单的例子中,我只使用assertEquals语句来比较roleService的id,但我仍然收到错误。 我有以下代码:

[更新]

测试方法:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = { "classpath:applicationContext.xml" })
@Transactional
@WebAppConfiguration
@ComponentScan(basePackages ={ "com.project.surveyengine" },
            excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, value = Configuration.class) ,
                              @ComponentScan.Filter(type = FilterType.ANNOTATION, value = WebConfig.class)})
public class RoleServiceTest {

@Configuration
    static class ContextConfiguration {    
        @Bean
        public RoleService roleService() {
            RoleService roleService = new RoleService();
            // set properties, etc.
            return roleService;
        }
    }

    private final LocalServiceTestHelper helper =
            new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig()
                    .setDefaultHighRepJobPolicyUnappliedJobPercentage(100));

    private Closeable closeable;

    @Before
    public void setUp() {
        helper.setUp();
        ObjectifyService.register(Role.class);
        closeable = ObjectifyService.begin();
    }

    @After
    public void tearDown() {
        closeable.close();
        helper.tearDown();
    }

    @Autowired
    private RoleService roleService;

    @Test
    public void existsRole() throws Exception{
        Role role = roleService.getByName("ROLE_ADMIN");
        assertEquals("Correct test", Long.valueOf("5067160539889664"), role.getId());
    }

}

RoleService是使用Google App Engine objectifyService查阅数据库信息的服务类。

applicationContext.xml中

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       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">

    <context:annotation-config /> 

    <context:component-scan base-package="com.project.surveyengine.config"/>

    <!--Controllers-->
    <bean id="inboxController" class="com.project.surveyengine.controller.InboxController" autowire="byType"></bean>
    <bean id="mailController" class="com.project.surveyengine.controller.MailController" autowire="byType"></bean>
    <bean id="loginController" class="com.project.surveyengine.controller.LoginController" autowire="byType"></bean>
    <bean id="initController" class="com.project.surveyengine.controller.InitController" autowire="byType"></bean>

    <!--Services-->
    <bean id="answerService" class="com.project.surveyengine.service.impl.AnswerService" autowire="byType"></bean>
    <bean id="blobService" class="com.project.surveyengine.service.impl.BlobService" autowire="byType"></bean>
    <bean id="mailService" class="com.project.surveyengine.service.impl.MailService" autowire="byType"></bean>
    <bean id="caseService" class="com.project.surveyengine.service.impl.CaseService" autowire="byType"></bean>
    <bean id="roleService" class="com.project.surveyengine.service.impl.RoleService" autowire="byType"></bean>
</beans>

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

1)

public class MyXmlWebApplicationContext extends XmlWebApplicationContext {
    protected void initBeanDefinitionReader(XmlBeanDefinitionReader beanDefinitionReader) {
        super.initBeanDefinitionReader(beanDefinitionReader);
        if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Production) {
            beanDefinitionReader.setValidating(false);
            beanDefinitionReader.setNamespaceAware(true);
        }
    }
}

2)

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter{    
  @Bean
  UrlBasedViewResolver resolver(){
    UrlBasedViewResolver resolver = new UrlBasedViewResolver();
    resolver.setPrefix("/views/");
    resolver.setSuffix(".jsp");
    resolver.setViewClass(JstlView.class);
    return resolver;
  }

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/statics/**").addResourceLocations("/statics/");
  }    
}

3)

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityContext extends WebSecurityConfigurerAdapter {    
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/statics/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .formLogin()
                //...more code
    }
}

我收到这个错误:

2016年12月20日4:40:03 PM com.google.appengine.api.datastore.dev.LocalDatastoreService初始化INFO:本地数据存储已初始化:类型:高复制存储:内存

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

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

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

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

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = { "classpath:applicationContext.xml" })
@TransactionConfiguration(transactionManager="txMgr", defaultRollback=false)
@Transactional
@WebAppConfiguration
@ComponentScan(basePackages ={ "com.project.surveyengine" }, excludeFilters = {
                @ComponentScan.Filter(type = FilterType.ANNOTATION, value = Configuration.class) })
public class RoleServiceTest {

    @Autowired
    private RoleService roleService;

    @Test
    public void existsRole() throws Exception{
        Role role = roleService.getByName("ROLE_ADMIN");
        assertEquals("Correct test", Long.valueOf("5067160539889664"), role.getId());
    }

}

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

我希望这可以帮助你

链接地址: http://www.djcxy.com/p/37321.html

上一篇: How to get Database connection in Spring using JUnit?

下一篇: Firefox WebExtension: Make XMLHttpRequest