【问题标题】:Spring-test unexpectedly fails, how best triangulate the error?Spring-test 意外失败,如何最好地对错误进行三角测量?
【发布时间】:2014-04-22 16:29:33
【问题描述】:

这个 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 文件,以免把所有空间都弄得乱七八糟。

【问题讨论】:

    标签: java spring-3 spring-test


    【解决方案1】:

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

    假设applicationContext.xmlwebmvc-config.xml 分别是您的rootDispatcherServlet WebApplicationContexts 的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 测试类实际上必须声明为abstract。 ;)

    问候,

    Sam(Spring TestContext 框架的作者)

    【讨论】:

    • 谢谢你的建议,山姆。我也必须添加括号(编辑上面的代码),但这解决了我的问题,谢谢!我应该质疑没有在名称中使用“Abstract”创建一个'类,嗯,抽象,但我从Spring-MVC-Showcase 借用了基本结构,并且必须假设这是正确的做法。感谢您也指出新手错误。
    • 很高兴它对你有用!并感谢您指出缺少的括号。我只是在没有 IDE 的情况下输入了该代码。 ;) 我现在已经修复了这个例子。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-08
    • 1970-01-01
    • 2015-06-22
    • 2017-07-28
    • 1970-01-01
    • 2018-09-16
    • 2016-03-25
    相关资源
    最近更新 更多