class Elephant extends Animal {   
    public Elephant(String name) {
        super(name);
    }
    void makeNoise() {
        logger.info(" Elephant  make Sound");
    }
    void perform(String day) {
        if (day.equals("thursday") || day.equals("friday")) {
            makeNoise();
        }
    }
}
Now i want to test the perform method. How can I unit test this method using JUnit?
import org.junit.Test;
import static org.mockito.Mockito.*;
public class ElephantTest {
    @Test
    public void shouldMakeNoise() throws Exception {
        //given
        Elephant elephant = spy(new Elephant("foo"));
        //when
        elephant.perform("friday");
        //then
        verify(elephant).makeNoise();
    }
}
Negative tests:
@Test
public void elephantShouldDontMakeNoisesOnMonday() {
    //given
    Elephant elephant = spy(new Elephant("foo"));
    //when
    elephant.perform("monday");
    //then
    verify(elephant, never()).makeNoise();
}
or
@Test
public void shouldDoNotMakeNoisesOnMonday() {
    //given
    Elephant elephant = spy(new Elephant("foo"));
    //when
    elephant.perform("monday");
    then(elephant).should(never()).makeNoise();
}
Dependency
org.mockito:mockito-core:2.21.0
Read about
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With