测试模型是否包含某些属性及其值

时间:2016-09-09 12:00:58

标签: java spring junit4

我正在尝试为Java Spring Framework实施一个简单的测试。以下是我的代码。

我的控制器:

@RequestMapping(value = "/someMapping", method = RequestMethod.GET)
public String toTestMethod(Model model)
{
   model.addAttribute("test", 1);
   return "test";    
}

控制器测试:

@Autowired
private WebApplicationContext wac;

private MockMvc mockMvc;

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

@Test
public void testMethodTest() throws Exception
{
    this.mockMvc.perform(get("/someMapping"))
    .andDo(print())
    .andExpect(status().isOk())
    .andExpect(model().attribute("test", 1));
}

申请背景:

@Configuration
@EnableWebMvc
public class WebAppContext extends WebMvcConfigurerAdapter
{

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

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer)
    {
        configurer.enable();
    }

    @Bean
    public ViewResolver viewResolver()
    {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();

        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/jsp/");
        viewResolver.setSuffix(".jsp");

        return viewResolver;
    }
}

当我运行此测试时,它失败并出现以下异常

java.lang.AssertionError: Model attribute 'test' expected:<1> but was:<null>

我不知道为什么会这样,有人可以澄清一下吗?

如果需要,我会提供任何其他信息。

1 个答案:

答案 0 :(得分:0)

所以,就我而言,问题出在setup(),现在看起来像这样:

@Before
public void setup()
{

    //        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();

    MyController ctrl = new MyController();
    this.mockMvc = MockMvcBuilders.standaloneSetup(ctrl).build();
}

在此次更改后,它开始按预期工作。