Spring MVC:如何从返回String的控制器方法单元测试Model的属性? [英] Spring MVC: How to unit test Model's attribute from a controller method that returns String?
本文介绍了Spring MVC:如何从返回String的控制器方法单元测试Model的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,
package com.spring.app;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* Handles requests for the application home page.
*/
@Controller
public class HomeController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(final Model model) {
model.addAttribute("msg", "SUCCESS");
return "hello";
}
}
我想测试 model
的属性及其来自 home()
的值,使用JUnit。我可以将返回类型更改为 ModelAndView
以使其成为可能,但我想使用 String
因为它更简单。但这不是必须的。
I want to test model
's attribute and its value from home()
using JUnit. I can change return type to ModelAndView
to make it possible, but I'd like to use String
because it is simpler. It's not must though.
无论如何检查 model
而不更改 home()
的退货类型?或者它无法帮助?
Is there anyway to check model
without changing home()
's return type? Or it can't be helped?
推荐答案
你可以使用 Spring MVC Test :
mockMvc.perform(get("/"))
.andExpect(status().isOk())
.andExpect(model().attribute("msg", equalTo("SUCCESS"))) //or your condition
并此处完全说明了示例
这篇关于Spring MVC:如何从返回String的控制器方法单元测试Model的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文