假设您有以下逻辑:
processMissing(masterKey, masterValue, p.getPropertiesData().get(i).getDuplicates());
public StringBuffer processMissing(String keyA, String valueA, Set<String> dupes) {
// do some magic
}
我想为 processMissing 编写一个 jUnit 测试,测试其在事件 dupes 中的行为为 null。
我在这里做的事情正确吗?我应该检查方法在 null 下的处理方式,或者测试方法调用以确保永远不会发送 null 吗?
一般来说,这里的方法是什么?我们无法测试所有的事情。我们也无法处理所有可能的情况。
在决定编写哪些测试时应该如何思考?
我的想法是这样的:
- 我对测试方法有一定的期望
- ,应该确认定义我的期望并确认方法在该条件下有效
这是思考它的正确方法吗?
谢谢,请告诉我
Suppose that you have the following logic in place:
processMissing(masterKey, masterValue, p.getPropertiesData().get(i).getDuplicates());
public StringBuffer processMissing(String keyA, String valueA, Set<String> dupes) {
// do some magic
}
I would like to write a jUnit test for processMissing, testing its behavior in event dupes is null.
Am i doing the right thing here? Should I check how method handles under null, or perhaps test method call to make sure null is never sent?
Generally speaking, what is the approach here? We can't test everything for everything. We also can't handle every possible case.
How should one think when deciding what tests to write?
I was thinking about it as this:
- I have a certain expectation with the method
- Test should confirm define my expectation and confirm method works under that condition
Is this the right way to think about it?
Thanks and please let me know
发布评论
评论(2)
首先,定义 null 是否是参数的有效值。
如果是,那么是的,一定要使用 null 来测试该方法的行为。
如果不是,则:
静态分析工具FindBugs支持@NonNull等注释,但数据流分析有限。
我个人认为,在大型 Java 代码库中总是编写和维护对 NULL 和相应的非本地单元测试的显式检查会不必要地昂贵。
First, define whether null is a valid value for the parameter or not.
If it is, then yes, definitely test the behavior of the method with null.
If it is not, then:
The static analysis tool FindBugs supports annotations such as @NonNull, with some limited data-flow analysis.
I personally think it would be unnecessarily expensive within large Java codebases to always write and maintain explicit checks for NULL and corresponding, non-local unit tests.
如果您想确保人们不会使用 null 参数调用您的 API,您可能需要考虑使用注释来明确这一点,JSR 305 涵盖了这一点,并且它在 Guava 中使用。否则,您将依赖用户阅读 javadoc。
至于测试,你不能处理所有可能的情况,假设你不想支持空值,我想说你可能想抛出一个 IllegalArguemntException 而不是 NullPointerException 这样你就可以明确什么是 null,然后您可以测试抛出的异常 - 请参阅 JUnit 文档。
If you want to ensure that people don't call your API with a null argument you may want to consider using annotations to make this explicit, JSR 305 covers this, and its used in Guava. Otherwise you're relying on users reading javadoc.
As for testing, you're spot on in that you can't handle every possible case, assuming you don't want to support null values, I'd say that you may want to throw an IllegalArguemntException rather than a NullPointerException so you can be explicit about what is null, then you can just test for that exception being thrown - see JUnit docs.