简体   繁体   中英

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.
    }
}

Since you're not testing the interface (no code to test in there) but the implementation. There is no need to mock the interface. You don't want to mock the code you're testing in any case. You want to mock everything the code you're testing uses.

So supposed the 'Magic' part is in another class, you want to mock this one. If it isn't you might want to refactor your class until it is because then it's violating the Single-Responsibility-Principle since doing magic and saying hello seem to be very different concerns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM