Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I unit test void functions?

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?

like image 360
user3156443 Avatar asked Mar 20 '23 21:03

user3156443


1 Answers

Solution with Mockito Spy

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

  • Mockito#doNothing()
  • Mockito#spy(T)
like image 65
MariuszS Avatar answered Mar 28 '23 02:03

MariuszS