简体   繁体   中英

how can a write a test case for this void method?

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:

  1. 'not' in method names is bad; .StringUtils.isBlank() would be more readable.
  2. It is wrong; it will answer 'false' if you pass in null, and that is incorrect. null is not some sort of alternative take on the notion of an empty string. 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.
  3. Java already has this! Just call path.isBlank() . Or rather, .path.isBlank() .

void methods can be tested

  1. If they having any object as parameter, after a method call those parameters can be asserted
  2. If the methods throwing any exceptions, we can assert whether the method throwing exceptions or not

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM