[英]Calling Junit Assertions via method call
I'm writing a Junit 4
test class comprising of 5 test methods.我正在编写一个包含 5 个测试方法的
Junit 4
测试类。 All these 5 test methods have same 10 assertEquals
lines of code.所有这 5 个测试方法都有相同的 10 行
assertEquals
代码。
Would it be best practice to move these lines of codes in one method for eg public void callAssertions() { .... }
and call this method from all tests?将这些代码行移动到一种方法中是否是最佳实践,例如
public void callAssertions() { .... }
并从所有测试中调用此方法?
As matt freake's comment mentions - Calling Junit Assertions via method call , there are differing opinions, but what I would do is separate assertions that are similar in nature.正如 matt freake 的评论所提到的 - 通过方法调用调用 Junit 断言,有不同的意见,但我会做的是性质相似的单独断言。
So for example if you want to assert person's details, I would separate them into an assertPersonDetails()
method - and so forth for other assertions.因此,例如,如果您想断言人的详细信息,我会将它们分成一个
assertPersonDetails()
方法 - 其他断言依此类推。 It really depends on the business logic underneath.这实际上取决于下面的业务逻辑。
I wouldn't recommend separating them all into a generic named method like you suggested callAssertions()
我不建议像你建议的
callAssertions()
那样将它们全部分离成一个通用的命名方法
As with all code, you should make sure that every test and every method in your test is readable and comprehensible.与所有代码一样,您应该确保每个测试和测试中的每个方法都是可读和可理解的。
You should have a clear pattern in your top test methods: given X, when Y, then Z. You can extract common code from each of the given/then/when parts, but you should not mix them.你的顶级测试方法应该有一个清晰的模式:给定 X,当 Y,然后 Z。你可以从每个给定/然后/当部分中提取公共代码,但你不应该混合它们。
So an assertThatZzzIsConsistent(...) method is OK, if it extracts only from the 'then' part.所以 assertThatZzzIsConsistent(...) 方法是可以的,如果它只从“then”部分提取。 But an executeYyyAndAssertThatZzzIsConsistent(...) is not OK if it combines the 'when' and 'then' part.
但是,如果 executeYyyAndAssertThatZzzIsConsistent(...) 结合了 'when' 和 'then' 部分,则它是不合适的。
I think that is a neater solution yes.我认为这是一个更简洁的解决方案,是的。 Personally i always keep everything as separate as possible so every test is completely standalone.
就我个人而言,我总是尽可能将所有内容分开,因此每个测试都是完全独立的。 As long as that is the case it's okay.
只要是这种情况就可以了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.