Pregunta

I have this MVC Controller:

@RequestMapping(produces = "text/html")
public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, @RequestParam(value = "sortFieldName", required = false) String sortFieldName, @RequestParam(value = "sortOrder", required = false) String sortOrder, Model uiModel) {
    if (page != null || size != null) {
        int sizeNo = size == null ? 10 : size.intValue();
        final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
        uiModel.addAttribute("smaker", Smak.findSmakEntries(firstResult, sizeNo, sortFieldName, sortOrder));
        float nrOfPages = (float) Smak.countSmaker() / sizeNo;
        uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
    } else {
        uiModel.addAttribute("smaker", Smak.findAllSmaker(sortFieldName, sortOrder));
    }
    return "smaker/list";
}

}

I use Tiles 2.2.2 and I have this view renders when the web app runs in Jetty, but I wanted to evaluate spring-test so I started with this simple test:

@RunWith(SpringJUnit4ClassRunner.class)
public class ViewsControllerTests extends AbstractContextControllerTests {

    private MockMvc mockMvc;

    @Before
    public void setup() throws Exception {
        this.mockMvc = webAppContextSetup(this.wac).alwaysExpect(status().isOk()).build();
    }//wac is in the superclass which loads it from file

    @Test
    public void getSmakerView() throws Exception {
        this.mockMvc.perform(get("/smaker"))
                .andExpect(view().name(containsString("smaker/list")));
    }

}

Indeed I have Rendering view [org.springframework.web.servlet.view.tiles2.TilesView name 'smaker/list'; in the logs when I run this project in Jetty.

Yet when I run tests the test above it fails with

java.lang.AssertionError: Expected: a string containing "smaker/list but: was "uncaughtException"

which is my default ErrorView for my SimpleMappingExceptionResolver. So something would seem to be wrong with either my test or my assumptions on what it does. Any ideas what my mistake could be here?

¿Fue útil?

Solución

The problem is caused by the call of

uiModel.addAttribute("smaker", Smak.findAllSmaker(sortFieldName, sortOrder));

especially this part: Smak.findAllSmaker Without any application context and resulting dependency injection or mocking this line will produce the problem you are facing.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top