使用 TestContext Framework 进行 Spring 和测试

标签 spring testing junit

我想为使用 Spring MVC 的应用程序编写一些单元测试。我阅读了 Spring 主页上的手册页:http://static.springsource.org/spring/docs/current/spring-framework-reference/html/testing.html 看来这Spring 测试框架可能真的很有用。

但这里有问题:

1.如果我理解正确,要使用任何注释进行测试,如 @ContextConfiguration 我需要使用 @RunWith(SpringJUnit4ClassRunner.class)?但是是否可以使用两个运行者(可能不行),我只是想知道是否可以使用 Spring 运行者和 mockito 一个,因为我正在使用 mockito 来模拟普通对象。

2.我有一个关于使用@ContextConfiguration加载xml上下文文件的问题。我在 src/main/webapp/WEB-INF/spring 中有我的 .xml 文件,如何使用 ContextConfiguration 加载它们?我试过了

@ContextConfiguration(locations="/webapp/WEB-INF/spring/root-context.xml")
@ContextConfiguration(locations="webapp/WEB-INF/spring/root-context.xml")
@ContextConfiguration(locations="/WEB-INF/spring/root-context.xml")
@ContextConfiguration(locations="WEB-INF/spring/root-context.xml")
@ContextConfiguration(locations="/src/main/webapp/WEB-INF/spring/root-context.xml")
@ContextConfiguration(locations="src/main/webapp/WEB-INF/spring/root-context.xml")

但我总是得到 class path resource [some_path] cannot be opened because it does not exist。我想知道我应该使用什么路径?

编辑: 第二个问题是 WEB-INF 不在类路径中,这是帮助我的主题 Location of spring-context.xml

最佳答案

  1. 不,您不能有两个@RunWith,您应该使用Mockito 提供的其他方式来创建Mock 替代。

  2. 指定多个位置的方式是这样的:

    @ContextConfiguration(locations={"first.xml", "second.xml"})
    

关于使用 TestContext Framework 进行 Spring 和测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12042834/

相关文章:

java - 无法在 Spring boot 中反序列化嵌套对象 "Role"

java - 微服务和 jpa

angular - 我怎样才能有条件地允许导航到用户

android - 配置 Android In App purchase 以进行测试

java - 如何记录资源包 key 缺失

java - 从 Spring 中的其余 Controller 返回错误消息和描述的问题

html - rspec 测试失败,但应该通过

java - Getter 和assertEquals 函数

java - 有没有一种通用的方法可以将 JUnit 测试标记为待处理?

java - 测试数组类类型对象时出现 Eclipse ClassNotLoadedException