从控制器测试的上下文访问 ModelAndView 对象中包含的模型的属性

发布于 2024-10-01 00:57:46 字数 1798 浏览 4 评论 0原文

我是 Spring MVC 的新手,我正在学习如何测试我的控制器。我有一个简单的测试:

@Test
public void shouldDoStuff()
{
    request.setRequestURI("/myCompany/123");
    ModelAndView mav = controller.getSomeDatas("123", request);
    assertEquals(mav.getViewName(), "company");
    assertTrue(mav.getModel().containsKey("companyInfo"));
    assertTrue(mav.getModel().containsKey("rightNow"));
    assertEquals(mav.getModel().get("companyInfo"), "123");
}

这是我的控制器操作:

@RequestMapping(value = "/myCompany/{companyGuid}", method = RequestMethod.GET)
public ModelAndView getSomeDatas(@PathVariable("companyGuid") String myGuid, HttpServletRequest request)
{
    /*ModelAndView mav = new ModelAndView("company");
    mav.addObject("companyInfo", myGuid);
    mav.addObject("rightNow", (new Date()).toString());
    return mav;*/
    Map<String, Object> myModel = new HashMap<String, Object>();

    myModel.put("companyInfo", myGuid);
    myModel.put("rightNow", (new Date()).toString());

    return new ModelAndView("company", "model", myModel);
}

我在第一个断言上设置了一个断点。在 Eclipse 的“显示”窗口中,mav.getModel() 返回的正是我所期望的:

mav.getModel()
 (org.springframework.ui.ModelMap) {model={rightNow=Fri Nov 05 13:30:57 CDT 2010, companyInfo=123}}

但是,任何访问该模型中的值的尝试都会失败。例如,我假设以下内容可行:

mav.getModel().get("companyInfo")
 null
mav.getModel().containsKey("companyInfo")
 (boolean) false

但如您所见,get("companyInfo") 返回 null,并且 containsKey("companyInfo") 返回 false。

当我用未注释的部分替换控制器的注释部分时,我的测试工作正常,但随后我的 jsp 视图中断,因为我试图通过诸如 ${model.companyInfo} 之类的内容来访问模型的属性,所以

我需要至少知道两件事之一(但如果你能回答这两件事就更好了):

  1. 如果我将控制器保留为如图所示,我如何在测试中访问模型的属性?
  2. 如果我将注释部分替换为未注释部分,我如何在 jsp 视图中访问模型的属性?

任何帮助表示赞赏。

I am new to Spring MVC and I'm in the process of learning how to test my controllers. I have a simple test:

@Test
public void shouldDoStuff()
{
    request.setRequestURI("/myCompany/123");
    ModelAndView mav = controller.getSomeDatas("123", request);
    assertEquals(mav.getViewName(), "company");
    assertTrue(mav.getModel().containsKey("companyInfo"));
    assertTrue(mav.getModel().containsKey("rightNow"));
    assertEquals(mav.getModel().get("companyInfo"), "123");
}

Here's my controller action:

@RequestMapping(value = "/myCompany/{companyGuid}", method = RequestMethod.GET)
public ModelAndView getSomeDatas(@PathVariable("companyGuid") String myGuid, HttpServletRequest request)
{
    /*ModelAndView mav = new ModelAndView("company");
    mav.addObject("companyInfo", myGuid);
    mav.addObject("rightNow", (new Date()).toString());
    return mav;*/
    Map<String, Object> myModel = new HashMap<String, Object>();

    myModel.put("companyInfo", myGuid);
    myModel.put("rightNow", (new Date()).toString());

    return new ModelAndView("company", "model", myModel);
}

I have a breakpoint set on the first assert. In the Display window in Eclipse, mav.getModel() returns exactly what I'd expect:

mav.getModel()
 (org.springframework.ui.ModelMap) {model={rightNow=Fri Nov 05 13:30:57 CDT 2010, companyInfo=123}}

However, any attempt to access the values in that model fails. For example, I assumed the following would work:

mav.getModel().get("companyInfo")
 null
mav.getModel().containsKey("companyInfo")
 (boolean) false

But as you can see, get("companyInfo") returns null, and containsKey("companyInfo") returns false.

When I swap out the commented section of the controller with the uncommented section, my tests work just fine, but then my jsp view breaks, because I'm trying to access properties of the model by saying things like ${model.companyInfo}, etc.

So I need to know at least one of two things (but better if you can answer both):

  1. If I leave the controller as shown, how can I access the attributes of the model in my test?
  2. If I swap out the commented section for the uncommented section, how can I access the attributes of the model in my jsp view?

Any help is appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

霞映澄塘 2024-10-08 00:57:46

对于问题 1,Model 提供了一种以映射形式返回模型属性的方法。在您的测试中,您可以执行以下操作:

Map<String,Object> modelMap = mav.getModel().asMap();
modelMap.get("companyInfo");

假设您将 companyInfo 设置到模型中,它应该在那里。

至于问题的第二部分,我想其他人已经回答了。

For question 1, Model provides a method that returns the model attributes as a map. In your test, you can do:

Map<String,Object> modelMap = mav.getModel().asMap();
modelMap.get("companyInfo");

Assuming you set companyInfo into the model, it should be there.

As for part2 of the question, I think someone else answered that already.

未蓝澄海的烟 2024-10-08 00:57:46

好吧,现在清楚了!

尝试:

mav.getModel().get("model");
mav.getModel().containsKey("model");

您在控制器中将模型映射称为“模型”...

在您的 jsp 中,我建议使用 Jstl:

<%@page contentType="text/html; charset=utf-8" pageEncoding="UTF-8" language="java"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html SYSTEM "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <body>
     ${model.companyInfo}
    </body>
</html>

Ok, now its clear!

Try:

mav.getModel().get("model");
mav.getModel().containsKey("model");

You called your modelmap 'model' in your controller...

In your jsp i would recommend using Jstl:

<%@page contentType="text/html; charset=utf-8" pageEncoding="UTF-8" language="java"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html SYSTEM "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <body>
     ${model.companyInfo}
    </body>
</html>
颜漓半夏 2024-10-08 00:57:46

您忘记使用视图名称调用 ModelAndView 的构造函数,并且忘记将对象添加到模型中。

我认为你的代码应该看起来像这样......

@Test
public void shouldDoStuff()
{
    request.setRequestURI("/myCompany/123");
    // call the constructor with the name of your view        
    ModelAndView mav = new ModelAndView("viewName"); 
    // add the objects to the model        
    mav.addAllObjects(controller.getSomeDatas("123", request));
    assertEquals(mav.getViewName(), "viewName");
    assertTrue(mav.getModel().containsKey("companyInfo"));
}

如果你需要使用自定义键添加多个对象,请使用 addObject 方法;

  mav.addObject("key1", 1);
  mav.addObject("key2", 2);

You forgot to call the constructor of ModelAndView with the viewname, and you forgot to add your objects to the model.

I think you code should look something like this...

@Test
public void shouldDoStuff()
{
    request.setRequestURI("/myCompany/123");
    // call the constructor with the name of your view        
    ModelAndView mav = new ModelAndView("viewName"); 
    // add the objects to the model        
    mav.addAllObjects(controller.getSomeDatas("123", request));
    assertEquals(mav.getViewName(), "viewName");
    assertTrue(mav.getModel().containsKey("companyInfo"));
}

If you need to add more than one object with custom keys use the addObject method instead;

  mav.addObject("key1", 1);
  mav.addObject("key2", 2);
一个人练习一个人 2024-10-08 00:57:46

@pedrofalcaocosta,我对你的答案投赞成票,因为它帮助我找到了答案,但我认为在这里回答我自己的问题是合适的:

((java.util.HashMap<String,Object>)mav.getModel().get("model")).get("companyInfo")

@pedrofalcaocosta, I'm giving your answer an up vote because it helped me find my answer, but I think it's appropriate to answer my own question here:

((java.util.HashMap<String,Object>)mav.getModel().get("model")).get("companyInfo")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文