Unit testing Boolean method based on other methods return types

whisk :

New to unit testing and am looking for a way to unit test a Boolean method that is validated by two other methods results.

 protected boolean isUpdateNeeded(){ 
 return (method1() && method2()); 
}

the other methods look like this for this example.

protected boolean method1() { 
 return false; 
}

protected boolean method2() { 
 return true; 
} 

But these two methods are/can be Overriden if need be. Idk if that really matter at this point

So my thinking behind the test is this. Find a way to pass true/false to method1 or method2 to meet the required possible outcomes.

@Test
 public void testCheckToSeeIfUpdateIsNeeded(){ 
   assertTrue('how to check here'); 
   asserFalse('how to check here');
   assertIsNull('was null passed?');  

 }
munk :

If another class extends this and overrides method1 and method2, it's the responsibility of the person developing that class to test the change.

You could mock method1 and method2, but you're then coupling the structure of your class with your test cases, making it harder to make a change later.

Your responsibility here to test the behavior of your class. I see the method in question is called isUpdateNeeded. So let's test that. I'll fill out the class as I imagine it.

class Updater {
    Updater(String shouldUpdate, String reallyShouldUpdate) {...}
    boolean method1() { return shouldUpdate.equals("yes"); }
    boolean method2() { return reallyShouldUpdate.equals("yes!"); }
    boolean isUpdateNeeded() { ...}
}

class UpdaterTest {
    @Test
    void testUpdateIsNeededIfShouldUpdateAndReallyShouldUpdate() {
        String shouldUpdate = "yes";
        String reallyShouldUpdate = "yes!"
        assertTrue(new Updater(shouldUpdate, reallyShouldUpdate).isUpdateNeeded());
    }
    .... more test cases .....
}

Notice how this test asserts the behavior of the Updater given the inputs, not it's relationship to the existence of some other methods.

If you would like the test to demonstrate what happens if you override the methods, subclass Updater in the test and make the appropriate change.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324955&siteId=1