您是否可以编写 Junit 风格的单元测试而不明确使用“assertEquals”,异常会导致测试失败
我注意到一些单元测试,例如在 spring 框架中,您设置对象和测试,但不明确使用断言方法。
本质上,你是否有例外。
这是单元测试吗? 这是要避免的事情吗? 例如,下面是来自 Spring 框架的一些测试。 没有断言子句,只是一个测试。
public void testNeedsJoinPoint() {
mockCollaborator.needsJoinPoint("getAge");
mockControl.replay();
testBeanProxy.getAge();
mockControl.verify();
}
I noticed some unit tests, like in the spring framework where you setup the object and the test but don't explicitly use the assert methods.
Essentially, you have an exception or not.
Is this unit testing? Is this something to avoid?
For example, here are some tests from the Spring framework. No assert clauses, just a test.
public void testNeedsJoinPoint() {
mockCollaborator.needsJoinPoint("getAge");
mockControl.replay();
testBeanProxy.getAge();
mockControl.verify();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您所展示的测试充满了期望,但它们是以模拟对象的形式表达的。
有些测试可能完全没有断言,但对我来说仍然没问题,例如简单地加载 spring 上下文并(隐式)断言其有效性的测试。 我真的认为问题应该是这是否是一个好的测试。 有时可能是这样,有时这只是你能得到的最好的。 而且往往比什么都没有好得多。
The test you are showing is full of expectations, but they are expressed in terms of the mock object.
Some tests may be totally void of asserts and still be ok with me, for instance a test that simply loads the spring context and (implicitly) asserts its validity. I really think the question should be if it is a good test. Sometimes it may be, and sometimes it's just the best you can get. And it may often be a lot better than nothing.
每一个异常都会让测试失败。 因此,您可以使用自己的异常来破坏单元测试。
如果您阅读源代码,
assertXXX
将会向 TestRunner 抛出异常。 因此单元测试是建立在异常之上的。嘲笑绝对是无可避免的。 这很好,因为它可能鼓励隔离你的测试。
Every exception let the test fail. So you can use your own exceptions to break your Unit test.
If you read the source code, a
assertXXX
will throw an Exception to the TestRunner. So Unit tests are build upon exceptions.Mocking is definitely nothing to avoid. It's good, because it may encourage isolation of your tests.
如果您担心,请尝试破坏代码以确保测试有效。
If you're concerned, try breaking the code to make sure that the tests are effective.
我将此称为“冒烟测试”并且经常这样做。
这就像运行你的引擎并断言没有烟雾,即没有抛出异常。 就我个人而言,我认为这种风格很好(但是嘿,我也是提倡依赖测试的人:)
I call this "smoke testing" and do it very often.
It is like running your engine and assert that there is no smoke, ie no exceptions are thrown. Personally, I consider this good style (but hey, I am also the guy that promotes dependent test :)