2016-12-07 7 views
7

Próbuję przetestować poprawne informacje podane z DB za pomocą usług i prawidłową logikę metod. W tym prostym przykładzie używam tylko instrukcji assertEquals, aby porównać identyfikator podany dla roleService, ale wciąż dostaję błędy. Mam następujący kod:Jak uzyskać połączenie z bazą danych na wiosnę przy użyciu JUnit?

[AKTUALIZACJA]

metody badawczej:

@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 jest klasa usługa skonsultować informacje z bazy danych przy użyciu objectifyServiceGoogle App Engine.

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> 

Do com.project.surveyengine.config mam folliwing trzy klasy:

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 
    } 
} 

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)

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

Moja osobista opinia jest taka, że Przede wszystkim musisz zdecydować, jakiego rodzaju testujesz. Czy to naprawdę rodzaj testu integracji? Czy ma sens połączenie z prawdziwą bazą danych i skonfigurowanie wszystkich powiązanych zestawów znaków, aby można było zweryfikować złożoną logikę w swoim module? A może to tylko jednolity test_, który sprawdza, czy twoja usługa działa zgodnie z oczekiwaniami? Sprawa, w której można po prostu kpić z zależności usług (mockito, easy mock, itp.) I po prostu utworzyć instancję i zweryfikować wyniki swoich metod. Nie mogę powiedzieć z twojego opisu, ale wydaje mi się, że to drugie, stąd moja sugestia. – Morfic

+0

Tak, poprzednio używałem Mockito, ale mam kilka metod, które muszę wyśmiać kilka repozytoriów, więc staje się to skomplikowaną pracą. Pomysł polega na sprawdzeniu oczekiwanego wyniku ze złożonego modułu, ale również na połączeniu z wykorzystaniem rzeczywistych informacji z DB. Właśnie dlatego korzystam z usług w teście. –

+0

Wyjątek jest bardzo prosty - test nie może znaleźć komponentu bean 'defaultServletHandlerMapping'. Dzieje się tak z powodu klasy 'WebConfig', więc powinieneś dodać ją do filtrowania:' Filter (type = FilterType.ANNOTATION, value = Configuration.class), Filter (type = FilterType.ANNOTATION, value = WebConfig.class)}) ' – Enigo

Odpowiedz

3

Próbowałeś dodać @WebAppConfiguration jak zasugerowano w dokumentacji http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/context/web/WebAppConfiguration.html?

bym wirte kodu testowego w ten sposób

@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()); 
    } 

} 

jak widać dodałem @WebAppConfiguration adnotacji zbyt

Mam nadzieję, że to może pomóc

+0

Otrzymuję ten błąd: java.lang.NoClassDefFoundError: javax/servlet/SessionCookieConfig –

+0

Jest to związane z tym, że nie masz biblioteki pod ścieżką klasy; jesteś yuo używając maven? możesz dodać zależność API serwletów do pom.xml –

+0

Tak, używam programu maven. Dodałem też zależność servlet-api, więc błąd jest taki sam. –

Powiązane problemy