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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4109077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:43:02  来源:igfitidea点击:

Accessing the attributes of a model contained in a ModelAndView object from the context of a controller test

javaspring-mvcjunit

提问by Samo

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

我是 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");
}

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:

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

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.

但是正如您所看到的,get("companyInfo") 返回 null,containsKey("companyInfo") 返回 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.

当我用未注释的部分替换控制器的注释部分时,我的测试工作得很好,但是我的 jsp 视图中断了,因为我试图通过说 ${model.companyInfo} 之类的东西来访问模型的属性,等等。

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?
  1. 如果我如图所示离开控制器,如何在我的测试中访问模型的属性?
  2. 如果我将注释部分换成未注释部分,如何在我的 jsp 视图中访问模型的属性?

Any help is appreciated.

任何帮助表示赞赏。

采纳答案by Samo

@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:

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

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

回答by pedrofalcaocosta

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

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

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;

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

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

回答by pedrofalcaocosta

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:

在您的 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>

回答by sanimalp

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

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

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

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

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

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

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