我在使此测试正常工作时遇到问题。断言始终会失败,因为它无法验证总是为null的forwardedUrl。如果我删除此假设,则无法验证回报模型。我想这是由于缺少转发的网址。我的测试课程如下:

@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的初学者,并且对控制器测试不熟悉。

编辑:我忘了添加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);
    }
}


编辑:这是导致此问题的异常的完整堆栈跟踪:

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)

最佳答案

如果使用生产配置文件而不是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/" />

关于java - MockMvc:forwardedUrl为空,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20782970/

10-11 19:01