2013-10-02 2 views
6

내가이 클래스가 있습니다상태가 예상 <404> 스프링 테스트에

package controllers; 

    import static org.junit.Assert.*; 
    import static org.mockito.Mockito.mock; 
    import static org.mockito.Mockito.times; 
    import static org.mockito.Mockito.verify; 
    import static org.mockito.Mockito.when; 

    import java.util.HashSet; 

    import org.junit.Before; 
    import org.junit.Test; 
    import org.junit.runner.RunWith; 
    import org.mockito.InjectMocks; 
    import org.mockito.Mock; 
    import org.mockito.MockitoAnnotations; 
    import org.springframework.beans.factory.annotation.Autowired; 
    import org.springframework.test.context.ContextConfiguration; 


    import org.springframework.ui.Model; 
    import org.springframework.web.context.WebApplicationContext; 

    import com.epam.hhsystem.model.candidate.Candidate; 
    import com.epam.hhsystem.services.CandidateService; 
    import com.epam.hhsystem.web.controllers.CandidateMenuController; 
    import org.springframework.test.context.web.WebAppConfiguration; 
    import org.springframework.test.context.junit4.*; 
    import org.springframework.test.web.servlet.MockMvc; 
    import org.springframework.test.web.servlet.ResultActions; 
    import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; 
    import org.springframework.test.web.servlet.setup.MockMvcBuilders; 


    import org.springframework.test.web.servlet.request.*; 

    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; 
    import static org.hamcrest.Matchers.*; 
    import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; 


    @ContextConfiguration(locations = { "classpath:/test/BeanConfig.xml" }) 
    @RunWith(SpringJUnit4ClassRunner.class) 
    @WebAppConfiguration 
    public class CandidateControllerTest { 

     @Mock(name = "candidateService") 
     private CandidateService candidateService; 

     @InjectMocks 
     private CandidateMenuController candidateMenuController = new CandidateMenuController(); 

     @Autowired 
     WebApplicationContext wac; 

     MockMvc mockMvc; 

     @Before 
     public void before() { 
      MockitoAnnotations.initMocks(this); 
       this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).dispatchOptions(true).build(); 

     } 
@Test 
    public void testgoToCandidateMenuMockMvc() throws Exception { 
     //MockHttpServletRequestBuilder request = MockMvcRequestBuilders.get("/goToCandidateMenu"); 


     MockHttpServletRequestBuilder request = MockMvcRequestBuilders.get("/goToCandidateMenu"); 
     ResultActions result = mockMvc.perform(request); 
     result.andExpect(status().isOk()); 
    } 
} 

을 내가 그것을 실행하면 내가 볼 :

java.lang.AssertionError: Status expected:<200> but was:<404> 
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:60) 
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:89) 
at org.springframework.test.web.servlet.result.StatusResultMatchers$5.match(StatusResultMatchers.java:549) 
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:141) 
at controllers.CandidateControllerTest.testgoToCandidateMenuMockMvc(CandidateControllerTest.java:104) 
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) 
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) 
at java.lang.reflect.Method.invoke(Method.java:597) 
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44) 
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) 
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41) 
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20) 
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28) 
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74) 
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83) 
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72) 
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231) 
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88) 
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193) 
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52) 
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191) 
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42) 
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184) 
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) 
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71) 
at org.junit.runners.ParentRunner.run(ParentRunner.java:236) 
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174) 
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) 
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) 
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) 
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) 
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) 
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) 

컨트롤러 코드 :

@Controller 
public class CandidateMenuController extends AbstractController { 
... 
@RequestMapping("/goToCandidateMenu") 
    public String goToCandidateMenu() { 
     return "candidateMenu"; 
    } 
... 
} 

을 내 문제를 해결하도록 도와 줄 수 있습니까?

UPDATE BeanConfig.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:aop="http://www.springframework.org/schema/aop" 
     xmlns:context="http://www.springframework.org/schema/context" 
     xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang" 
     xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" 
     xmlns:util="http://www.springframework.org/schema/util" 
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd 
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd 
      http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd 
      http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd 
      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd 
      http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> 

     <!-- Включаем опцию использования конфигурационных аннотаций (@Annotation-based configuration)--> 
     <context:annotation-config /> 


     <context:component-scan base-package="com.epam.hhsystem.jpa" /> 
     <context:component-scan base-package="com.epam.hhsystem.services" /> 

     <!-- Файл с настройками ресурсов для работы с данными (Data Access Resources) --> 
     <import resource="data.xml" /> 

    </beans> 

인 data.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:aop="http://www.springframework.org/schema/aop" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang" 
    xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" 
    xmlns:util="http://www.springframework.org/schema/util" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd 
     http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd 
     http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd 
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd 
     http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> 

<!-- Настраивает управление транзакциями с помощью аннотации @Transactional --> 
    <tx:annotation-driven transaction-manager="transactionManager" /> 

    <!-- Менеджер транзакций --> 
    <bean id="transactionManager" 
     class="org.springframework.orm.hibernate4.HibernateTransactionManager"> 
     <property name="sessionFactory" ref="sessionFactory" /> 
    </bean> 

    <!-- Непосредственно бин dataSource --> 
    <bean id="dataSource" 
     class="org.springframework.jdbc.datasource.DriverManagerDataSource" 
     p:driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver" 
     p:url="jdbc:sqlserver://10.16.9.52:1433;databaseName=hhsystemTest;" 
     p:username="userNew" 
     p:password="Pass12345" /> 

    <!-- Настройки фабрики сессий Хибернейта --> 
    <bean id="sessionFactory" 
     class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> 
     <property name="dataSource" ref="dataSource" /> 
     <property name="configLocation"> 
      <value>classpath:test/hibernate.cfg.xml</value> 
     </property> 

     <property name="hibernateProperties"> 
      <props> 
       <prop key="hibernate.show_sql">true</prop> 
       <prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop> 
       <prop key="hibernate.connection.charSet">UTF-8</prop> 
<!--    <prop key="hibernate.hbm2ddl.auto">create-drop</prop> --> 
     </props> 
     </property> 
    </bean> 

</beans> 
+0

우리는 당신의 상황을보고해야합니다. 또한'mockMvc'는 어디서 초기화합니까? –

+0

로그 출력을보십시오. 404가 나오면 서버가 그 이유를 알려줍니다. – chrylis

+10

왜 누군가가 IMHO의 합법적 인 질문을 이렇게 downvote하겠습니까? –

답변

5

테스트 설정이 올바르게 MockMvc를 초기화하지 않는 잘못하고 명확하게 알입니다 참조 가이드. 두 번째로 초기화 코드가있는 것이 모두이며 build 메서드에 대한 호출 결과를 확인하는 것이 아닙니다. 따라서 기본적으로 빈 MockMvc 개체가 남습니다. 이 모든 the reference guide에 설명되어 언급 한 바와 같이

@Before 
public void before() { 
    MockitoAnnotations.initMocks(this); 
    MockMvcBuilders.webAppContextSetup(this.wac).dispatchOptions(true).build(); 
    MockMvcBuilders.webAppContextSetup(this.wac).dispatchOptions(true).build(); 
} 

@Before 
public void before() { 
    MockitoAnnotations.initMocks(this); 
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).dispatchOptions(true).build(); 
} 

작아야합니다.

+0

죄송합니다. 잘못된 코드를 게시했습니다. (게시 된 댓글). 내 코드는 귀하의 변형과 같습니다. 그러나 나는 오래된 문제가있다. 나는 내 게시물에 mustake 고정 – gstackoverflow

+0

이 외에도, 내 경우에는 URL의 시작 부분에 슬래시 "/"가 누락되었습니다. –

3

<mvc:annotation-driven>을 사용 설정하지 않았으므로 @Controller 클래스가 등록되지 않고있는 것 같습니다.

내가 구성 클래스에이 주석을 추가 한이

<mvc:annotation-driven></mvc:annotation-driven> 
1

추가하고 작업 :

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(loader = AnnotationConfigWebContextLoader.class) 
@WebAppConfiguration 
public class ResourceTest { 

    ... 

    @Configuration 
    @EnableWebMvc 
    @ComponentScan(basePackages = { "..." }) 
    static class ContextConfiguration { 
    } 
}