繁体   English   中英

弹簧测试意外失败,如何最好地对错误进行三角测量?

[英]Spring-test unexpectedly fails, how best triangulate the error?

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

显然,我没有测试我的想法。 有什么建议如何三角这个问题?

我将完整的Web MVC文件发布在Pastebin上 ,以免使此处的所有空间混乱。

仅供参考: @WebAppConfigurationvalue属性不是 XML配置文件,而是Web应用程序的目录。 因此,您当前的测试配置将永远无法正常工作。

假设applicationContext.xmlwebmvc-config.xml分别是您的rootDispatcherServlet 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的作者)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM