我是 JMock 的新手,正在尝试开发 Spring Controller 测试。这是我的测试方法:
@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 灵活。我无法访问模型属性,所以这里的最后一行代码不应该是这样。
最佳答案
我通常使用 Model
接口(interface),然后在测试父类(super class)中我有代码可以让我在 Model 中获取东西
@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);
}
}
然后在测试中我可以做
assertEquals("someValue", getModelValue("bean", String.class));
或
assertTrue(getModelValue("student", Student.class).getId() == "767001");
请注意,这只是此类代码的简写
Student student = (Student) model.asMap().get("student");
assertEquals(767001, student.getId());
关于spring - 使用 JMock 在 Spring 中测试 ModelMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13489926/