mardi 3 novembre 2015

Dealing with private Methods (Whitebox-Test) | Methods with many conditions

Ok So I have 2 questions:

1.) In JUnit you shouldn't test or mock private methods. But how do I deal with, when they are getting called inside a public method. Let's assume I have following Setup:

public void method(String value){
    if(value.contains("something")){
        doSomethingToString(value);
    }
    else{
        //do something else
    }
}

private void doSomethingToString(String value){
    Object obj = service.getObject();   //service is mocked in my test-class
    //do something with the obj and value
}

So this is just a basic example. The thing is, I am doing a Whitebox-test, so I know, the methods and what's going on. Now, I want to test the public method method(String value). When I now only consider, what happens in there, I would get into trouble, since I need to influence, what service.getObject() in my private method returns.

So is it ok, when I just go on, like I would, meaning using
doReturn(objectICreatedInMyTestClass).when(service.getObject()) or do I need to find another way?

2.) Now to methods which have more than one conditions. For example:

public void method(String value){
    if(value.contains("something")){
        Object obj = service.getObj(value);
    }
    else{
        //do something else
    }

    if(obj.getAddress == null){
        //do something
    }
    else{
        //do something else
        }

    if (obj.getName == "Name") {
        // do something
    } 
    else 
    {
        // do something else
    }
}

So how many times do I need to test this method? Only twice, where once all conditions return true, and second, where they all return false? Or is it advised to test every possible scenario? This would mean test with condition 1 = true, condition 2 = false, condition 3=false, and then condition 1 = true, condition 2 = true, condition 3 = false and so on (= 8 possibilites).

Keep in mind, these are very simple examples, but I currently am Unit-Testing many classes, and shouldn't refactor them currently, so I am facing some troubles.

Thanks!

Aucun commentaire:

Enregistrer un commentaire