Pergunta

This basic Spring test of a Spring 3 controller gives me a response code 404 result instead of the expected 200:

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

private MockMvc mockMvc;

@Before
public void setup() throws Exception {
this.mockMvc = webAppContextSetup(this.wac)
.alwaysExpect(status().isOk()).build();
}

@Test
public void viewIndex() throws Exception {
this.mockMvc.perform(get("/")).andExpect(view()
.name(containsString("index"))).andDo(print());
}

AbstractContextControllerTests:

@WebAppConfiguration("file:src/main/webapp/WEB-INF/spring/webmvc-config.xml")
@ContextConfiguration("file:src/main/resources/META-INF/spring/applicationContext.xml")
public class AbstractContextControllerTests {

@Autowired
protected WebApplicationContext wac; }

I have verified the controller method itself with another test, but when I use the context the test fails even as the controller does serve the proper page when run in container.

The controller in question looks like this:

@Controller
public class RootController {
@Autowired
CategoryService categoryService;    

    @RequestMapping(value = "/", method = RequestMethod.GET, produces = "text/html")
    public String index(Model uiModel) {    
            uiModel.addAttribute("categories", categoryService.findAll());
        return "index";
    }

Clearly I'm not testing what I think. Any suggestion how to triangulate this issue?

I posted the full web mvc file at Pastebin to not clutter all space up here.

Foi útil?

Solução

FYI: The value attribute for @WebAppConfiguration is not an XML configuration file but rather the root directory of your web application. So your current test configuration could never work.

Assuming that applicationContext.xml and webmvc-config.xml are the XML configuration files for your root and DispatcherServlet WebApplicationContexts, respectively, try redefining AbstractContextControllerTests as follows:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextHierarchy ({
  @ContextConfiguration("/META-INF/spring/applicationContext.xml"),
  @ContextConfiguration("file:src/main/webapp/WEB-INF/spring/webmvc-config.xml")
})
public abstract class AbstractContextControllerTests {

    @Autowired
    protected WebApplicationContext wac;

}

By the way, abstract test classes must actually be declared as abstract. ;)

Regards,

Sam (author of the Spring TestContext Framework)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top