How can I unit test execute 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 method perform. How can I unit test use this method using JUnit?

+1
source share
4 answers
Functions

void()change the state of the program. This can be done by changing the variable, file, database, etc.

In your case, you write to the registrar. If this leads to the recording of "Elephant make Sound" in a file, you can read this file and see if the data in the file contains your noisy elephant.

, , , ( : ), - (DI), - , .

, DI, , .

+2

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();

    }
}

org.mockito:mockito-all:1.9.5

+2

, , .

. , - - , "", - !

. , , ( , , . , . , , . , ). , / , :

String makeNoise() {
    return "Elephant  make Sound";
}

String perform(String day) {
    if (day.equals("thursday") || day.equals("friday")) {
      return makeNoise();
    }
}

, perform, , , :

 logger.info(perform(day));
0

, , .

Java

(MockElephant), , makeNoise, . , , makeNoise

, , MockElephant , . , . . , , . Mocking frameworks , .

, Partial Mocking, , ( ).

Normal Mocks, ( ).

Here you must enter Logger as a dependency. For example, you can create an additional constructor that allows you to provide Logger. In your test, you would use the ridiculous Logger, which again counts its invocations, probably together with the received parameter, and checks that it has the expected values.

Again, you can do this with the Mocking Framework or with plain old Java.

0
source

All Articles