I want to write a junit test case for this method
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.
I know void methods are usually not tested
That's... not true.
Make a getter for that link
field. You may make it package private (no access modifier at all) if you want, or even document it with @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.
NB: Don't use StringUtils. It's bad.
For example, StringUtils.isNotBlank
has a ton of problems:
null
means something along the lines of 'no value' or 'unknown'. 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()
. Or rather, .path.isBlank()
.void methods can be tested
Demo 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());
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.