Spring MVC:如何从返回字符串的控制器方法对模型的属性进行单元测试?

2024-02-24

例如,

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因为它更简单。但这不是必须的。

有什么办法可以检查吗model不改变home()的返回类型?还是没办法帮助?


您可以使用Spring MVC 测试 http://docs.spring.io/spring/docs/current/spring-framework-reference/html/integration-testing.html#spring-mvc-test-framework:

mockMvc.perform(get("/"))
                .andExpect(status().isOk())
                .andExpect(model().attribute("msg", equalTo("SUCCESS"))) //or your condition

And here https://www.petrikainulainen.net/programming/spring-framework/unit-testing-of-spring-mvc-controllers-normal-controllers/是充分说明的例子

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring MVC:如何从返回字符串的控制器方法对模型的属性进行单元测试? 的相关文章

随机推荐