mercredi 29 janvier 2020

How to mocking the implemented methods of a class under test in Spring Boot with Mockito

I am unsure after much reading how to test the class below.

I have given a basic example...but assuming the class/implemented method could produce a more complex object (not just a String as below), how can I mock the interface so I can inject a mock in to the class to test various class behaviours?

For example, in the oversimplified below...if the length of the 'sayHello' was more than 500chars when calling the class 'getSayHelloLength()', I may want to Assert a 'HelloTooLongException' is thrown.

/**
 * MyClass implements MyInterface.
 */
public class MyClass implements MyInterface {

    public int getSayHelloLength() {
        return sayHello().length();
    }

    //I want to change/Mock the return of the implemented interface.
    @Override
    public String sayHello() {

        //Do some magic and some code an eventually return something based upon 'input'
        // Magic
        // More magic.


        return "My Class to Test Says Hello!";
    }
}

The interface:

public interface MyInterface {
    String sayHello();
}

I am using JUnit5:

class MyClassTest {

    @InjectMocks
    private MyClass myClass;

    @BeforeEach
    void setUp() {
    }

    @Test
    void getSayHelloLength() {
        //Mock the interface 'myClass' implements as to test various "hellos" outputs.
    }
}

Aucun commentaire:

Enregistrer un commentaire