[英]how can a write a test case for this void method?
I want to write a junit test case for this method我想为这个方法写一个junit测试用例
public class LinkModel {
@Inject
@Optional
private String path;
private static final String CONTENTPATH="/content";
private String link;
@PostConstruct
protected void init(){
link=path;
if(StringUtils.isNotBlank(path) && isInternal()){
link=path+ "";
}
private boolean isInternal(){
return path.contains(CONTENTPATH);
}
public String getLink() {
return link;
}
}
I know void methods are usually not tested but this has some extra logic that should be tested.我知道 void 方法通常不经过测试,但这有一些额外的逻辑需要测试。
I know void methods are usually not tested我知道 void 方法通常不经过测试
That's... not true.这不是真的。
Make a getter for that link
field.为该link
字段创建一个吸气剂。 You may make it package private (no access modifier at all) if you want, or even document it with @ForTesting
.如果需要,您可以将其设为 package 私有(根本没有访问修饰符),或者甚至使用@ForTesting
记录它。 Now you can test that your method modifies link as desired (and if this is your real code, the test will fail; you don't change path at all; adding an empty string to a string like this doesn't change it. Unless path
is null, in which case, this replaces the null pointer with a pointer to the string "null"
. Which.. seems weird.现在您可以测试您的方法是否根据需要修改了链接(如果这是您的真实代码,则测试将失败;您根本不会更改路径;将空字符串添加到这样的字符串不会改变它。除非path
是 null,在这种情况下,这会将 null 指针替换为指向字符串"null"
的指针。这看起来很奇怪。
NB: Don't use StringUtils.注意:不要使用 StringUtils。 It's bad.这不好。
For example, StringUtils.isNotBlank
has a ton of problems:例如, StringUtils.isNotBlank
有很多问题:
null
means something along the lines of 'no value' or 'unknown'. null
的意思是“无价值”或“未知”。 If I ask you: "I have an unknown shirt. Is it red?", then the only sensible answer would be: "Um? I don't know.", Neither "Yes, it is red" nor "No. it is not" is correct.如果我问你:“我有一件不知名的衬衫。它是红色的吗?”,那么唯一明智的答案是:“嗯?我不知道。”,既不是“是的,它是红色的”,也不是“不。它”不是”是正确的。path.isBlank()
.只需调用path.isBlank()
。 Or rather, .path.isBlank()
.或者更确切地说, .path.isBlank()
。void methods can be tested void方法可以测试
Demo Class演示 Class
public class Demo
{ {
private String path="dummy";
private static final String CONTENTPATH="/content";
private String link;
protected void init()
{
if(path.length()>0)
{
link=path+ "";
}
}
private boolean isInternal()
{
return path.contains(CONTENTPATH);
}
public String getLink()
{
return link;
}
} }
Test Case测试用例
class DemoTest {
@Test
void test() {
Demo obj = new Demo();
obj.init();
assertEquals("dummy", obj.getLink());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.