一起使用 Spring JUnit4 和 JMock
当我现在运行 Junit4 测试时,我使用 @RunWith(SpringJUnit4ClassRunner.class) 注释,它允许我将 Spring Beans 注入到我的测试类中。
我想使用 JMock 2 框架(我没有真正的经验),但我看到的示例需要以下 @RunWith(JMock.class)
。
所以我的问题是我可以将 JMock 和 Spring 与我的 JUnit4 测试一起使用吗?如果可以的话怎么做?例如,是否有一个 Spring 测试运行器也支持 JMock?
谢谢,
理查德
When I run my Junit4 tests now I use the @RunWith(SpringJUnit4ClassRunner.class)
annotation which allows me to inject Spring Beans into my test class.
I would like to use the JMock 2 framework (which I have no real experience of) but examples I see require the following @RunWith(JMock.class)
.
So my question is can I use JMock and Spring together with my JUnit4 tests and if so how? For instance is there a Spring test runner that also supports JMock?
Thanks,
Richard
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在测试结束时显式调用
context.assertIsSatisfied()
,例如在@After
方法中。在 jmock.org 站点上,选择任何代码示例上的“其他”选项卡,文档将向您展示如何使用 jMock 而不集成 JUnit 框架。
jMock 的下一个版本将支持 JUnit 4.7 中的新“规则”机制,因此您不需要使用自定义测试运行程序。
You can explicitly call
context.assertIsSatisfied()
at the end of your test, in an@After
method for example.On the jmock.org site, select the "Other" tab on any code example and the documentation will show you how to use jMock without JUnit framework integration.
The next version of jMock will support the new "rules" mechanism in JUnit 4.7, and so you won't need to use a custom test runner.
如果问题与
@RunWith
有关,您可以使用 JMockit Expectations API 相反。它与 jMock 类似,期望也记录在
new Expectations() {...}
块中,但不需要使用@RunWith
(也不需要使用@RunWith
)。基础测试类)。此外,没有包装期望块的
context.checking(...)
方法调用。If the problem is related to
@RunWith
, you can use the JMockit Expectations API instead.It is similar to jMock in that expectations are also recorded inside a
new Expectations() {...}
block, but does not require the use of@RunWith
(nor a base test class).In addition, there is no
context.checking(...)
method call wrapping the expectation block.我想你可能还忽略了一点。对于单元测试,我希望精确控制被测对象的构造方式,这意味着将已知实例作为协作者传递。换句话说,如果我需要一个对象,那么我会在测试中创建它并将其传递进去。调用 Spring 似乎有点矫枉过正。
另一方面,如果我正在进行某种集成测试,我将需要Spring bean,以查看整个事情如何连接在一起或针对第三方组件进行测试。
I think you might also be missing a point here. For unit testing, I want exact control over how the object under test is constructed, which means passing in known instances as collaborators. In other words, if I need an object then I create it in the test and pass it in. Invoking Spring seems like overkill.
On the other hand, I would need Spring beans if I were doing some kind of integration test, to see how the whole thing wired together or test against a third-party component.