Question

I'm new to JMock, trying to develop a Spring controller test. Here is my test method:

@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));

The question is how I'm able to test if the model contains the right object and object values? ModelMap is not that flexible than e.g ModelAndWiew. I can't get access to model attributes so the last code line here is not how it should be.

Was it helpful?

Solution

I usually use the Model interface and then in a test super class I have code which allows me to get at things in the 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);
    }

}

then in a test I can do

assertEquals("someValue", getModelValue("bean", String.class));

or

assertTrue(getModelValue("student", Student.class).getId() == "767001");

Note this is all just shorthand for code like this

Student student = (Student) model.asMap().get("student");
assertEquals(767001, student.getId());

OTHER TIPS

You can use extended model map instead for more flexibility. And you should declare references using the interface not implementation.

There is also this package to be included in spring 3.2 which may help : https://github.com/SpringSource/spring-test-mvc

However I have always been fine using extendedmodelmap and plain old hashmaps.

In your example, have you implemented equals (and hashcode) correctly, if you have not overrridden these methods the assertEquals will be testing if the objects are the same reference.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top