使用JMock在Spring中测试ModelMap

使用JMock在Spring中测试ModelMap,spring,testing,jmock,Spring,Testing,Jmock,我是JMock的新手,尝试开发一个Spring控制器测试。以下是我的测试方法: @Test public void testList() { context.checking(new Expectations() {{ Student student = new Student(767001); oneOf(studentService).getByNumber(767001); will(returnValue(student)); }});

我是JMock的新手,尝试开发一个Spring控制器测试。以下是我的测试方法:

@Test
public void testList() {
    context.checking(new Expectations() {{
        Student student = new Student(767001);
        oneOf(studentService).getByNumber(767001); will(returnValue(student));
    }});    


    ModelMap model = new ModelMap();
    Student student = new Student(767001);
    model.addAttribute("student", student);
    CourseRightController instance = new CourseRightController();
    request.setMethod("GET");

    Assert.assertEquals(studentService.getByNumber(767001),model.get(student));

问题是我如何能够测试模型是否包含正确的对象和对象值?ModelMap没有ModelAndWiew那么灵活。我无法访问模型属性,因此这里的最后一行代码不是它应该的样子。

您可以使用扩展模型映射来提高灵活性。您应该使用接口而不是实现来声明引用

spring 3.2中还包含此软件包,它可能有助于:

然而,我一直很好地使用和平原老


在您的示例中,您是否正确地实现了equals(和hashcode),如果您没有过度使用这些方法,assertEquals将测试对象是否是相同的引用。

我通常使用
模型
接口,然后在一个测试超类中,我有代码,允许我获取模型中的内容

@Ignore
public abstract class SpringControllerTestCase {
    /**
     * Spring Model object - initialised in @Before method.
     */
    private Model model;

    /**
     * Initialise fields before each test case.
     */
    @Before
    public final void setUpAll() {
       model = new ExtendedModelMap();
    }

    public final Model getModel() {
        return model;
    }

    @SuppressWarnings("unchecked")
    public <T> T getModelValue(final String key, final Class<T> clazz) {
        return (T) getModel().asMap().get(key);
    }

}

关于这些断言,我不确定,因为我是新手。我试图测试这个模型是否包含正确的数据,这里的学生号码是767001,依靠模拟服务。应该如何做。模型实际上是如何初始化的?在超类
model=newextendedmodelmap()中的@Before方法中我将其添加到示例中
Student student = (Student) model.asMap().get("student");
assertEquals(767001, student.getId());