2013-12-26 5 views
2

У меня возникли проблемы с этой тестовой работой. Утверждение всегда терпит неудачу, потому что оно не может проверить forwardedUrl, который всегда равен нулю. Если я удалю это предположение, он не сможет проверить модель возврата. Полагаю, это из-за отсутствия переадресованного Url. Мой тестовый класс выглядит следующим образом: Файл конфигурацииMockMvc: forwardedUrl is null

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = {"classpath:test-application-config.xml"}) 
@WebAppConfiguration 
public class UserControllerTest { 
    private MockMvc mockMvc; 

    @Mock 
    private UserService userServiceMock; 

    @Inject 
    private WebApplicationContext wac; 

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

    @Test 
    public void users_ShouldAddUserEntriesToModelAndRenderUserListView() throws Exception { 
    User firstUser = generateSampleUser("Pera", "Peric"); 
    User secondUser = generateSampleUser("Maja", "Majic"); 

    when(userServiceMock.getAllUsers()).thenReturn(Arrays.asList(firstUser, secondUser)); 

    mockMvc.perform(get("/users")) 
     .andExpect(status().isOk()) 
     .andExpect(view().name("users")) 
     .andExpect(forwardedUrl("/WEB-INF/velocity/users.vm")) 
     .andExpect(model().attribute("users", hasSize(2))) 
     .andExpect(model().attribute("users", hasItem(
       allOf(
         hasProperty("id", is(1L)), 
         hasProperty("firstName", is("Pera")), 
         hasProperty("LastName", is("Peric")) 
       ) 
     ))) 
     .andExpect(model().attribute("users", hasItem(
       allOf(
         hasProperty("id", is(2L)), 
         hasProperty("firstName", is("Maja")), 
         hasProperty("LastName", is("Majic")) 
       ) 
     ))); 

    verify(userServiceMock, times(1)).getAllUsers(); 
    verifyNoMoreInteractions(userServiceMock); 
    } 

    private User generateSampleUser(String firstName, String lastName) { 
    User user = new User(); 
    user.setFirstName(firstName); 
    user.setLastName(lastName); 
    user.setEmail("[email protected]"); 
    user.setBirthday(new Date()); 
    user.setGender(Gender.MALE); 
    user.setPersonalNumber("1234567890123"); 

    return user; 
    } 
} 

И тест выглядит следующим образом:

<?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" 
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" 
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"> 

<import resource="classpath:data-config-hsql.xml" /> 

<mvc:annotation-driven /> 

<context:component-scan base-package="com.code9" /> 

<bean id="velocityConfig" 
    class="org.springframework.web.servlet.view.velocity.VelocityConfigurer"> 
    <property name="resourceLoaderPath" value="/WEB-INF/velocity/" /> 
</bean> 

<bean id="viewResolver" 
    class="org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver"> 
    <property name="cache" value="true" /> 
    <property name="prefix" value="" /> 
    <property name="layoutUrl" value="layout.vm" /> 
    <property name="suffix" value=".vm" /> 
    <property name="exposeSessionAttributes" value="true" /> 
</bean> 

Я должен отметить, что я просто новичок в Spring MVC, и что я m не знакомы с испытаниями контроллера.

Edit: Я забыл добавить реализацию UserController:

@Controller 
public class UserController { 

    @Inject 
    private UserService userService; 

    @RequestMapping(value = "/users", method = RequestMethod.GET) 
    public ModelAndView getAllUsers() { 
     List<User> users = userService.getAllUsers(); 

     return new ModelAndView("users", "users", users); 
    } 
} 

Edit: Это полная трассировка стека исключением того, что является причиной этой проблемы:

java.io.FileNotFoundException: class path resource [WEB-INF/velocity/] cannot be resolved to URL because it does not exist 
at org.springframework.core.io.ClassPathResource.getURL(ClassPathResource.java:177) 
at org.springframework.core.io.AbstractFileResolvingResource.getFile(AbstractFileResolvingResource.java:48) 
at org.springframework.ui.velocity.VelocityEngineFactory.initVelocityResourceLoader(VelocityEngineFactory.java:304) 
at org.springframework.ui.velocity.VelocityEngineFactory.createVelocityEngine(VelocityEngineFactory.java:234) 
at org.springframework.web.servlet.view.velocity.VelocityConfigurer.afterPropertiesSet(VelocityConfigurer.java:119) 
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1571) 
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1509) 
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521) 
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458) 
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296) 
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223) 
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293) 
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) 
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:628) 
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932) 
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479) 
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:120) 
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60) 
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:100) 
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:248) 
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContextInternal(CacheAwareContextLoaderDelegate.java:64) 
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:91) 
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:122) 
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:105) 
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:74) 
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:312) 
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211) 
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288) 
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) 
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:284) 
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:238) 
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) 
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) 
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) 
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) 
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:309) 
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) 
+0

Хорошо. Вот проблема: java.io.FileNotFoundException: ресурс пути класса [badminton/src/main/webapp/WEB-INF/скорость /] не может быть разрешен для URL-адреса, потому что его не существует. Мой вопрос заключается в том, как ссылаться на этот путь, который находится в другой исходной папке? –

+0

Пожалуйста, отправьте полную статистику стека. –

+0

Я добавил полную трассировку стека. –

ответ

0

ли работать это, если вы используете файлы конфигурации производства вместо вашего test-application-config?

например.

@ContextConfiguration({"file:src/main/webapp/WEB-INF/applicationContext.xml", 
    "file:src/main/webapp/WEB-INF/dispatcher-servlet.xml"}) 

Может быть, вам нужно добавить некоторые ../ в resourceLoaderPath.

например.

<property name="resourceLoaderPath" value="../main/webapp/WEB-INF/velocity/" />