春季测试意外失败,如何最好地三角测量错误



Spring 3控制器的这个基本Spring测试给了我一个响应代码404的结果,而不是预期的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; }

我已经用另一个测试验证了控制器方法本身,但当我使用上下文时,即使控制器在容器中运行时提供了正确的页面,测试也会失败。

有问题的控制器看起来像这样:

@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";
    }

很明显,我不是在测试我的想法。有什么建议可以对这个问题进行三角分析吗?

我在Pastebin发布了完整的web mvc文件,以免把这里的所有空间都弄得一团糟。

FYI:@WebAppConfigurationvalue属性不是XML配置文件,而是web应用程序的root目录。因此,您当前的测试配置永远无法工作。

假设applicationContext.xmlwebmvc-config.xml分别是DispatcherServlet WebApplicationContext的XML配置文件,请尝试按如下方式重新定义AbstractContextControllerTests

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

顺便说一句,抽象测试类实际上必须声明为abstract.;)

问候,

Sam(Spring TestContext Framework的作者)

最新更新