[JAVA] [Spring Boot] Mock the contents that are autowired outside the scope [JUnit 5]

background

Convert Bean to Mock to test the content involving Custom Validator such as using @ Autowired.

manner

The implementation is as follows, please refer to the comments for each explanation.

//If you attach these two@RunWith(MockitoJUnitRunner.class)No need for rules or rules
@ExtendWith(SpringExtension.class)
@SpringBootTest
class HogeTest {
    //Mock the bean, this instance is injected
    @MockBean FugaDao fugaDao;

    @Test
    @DisplayName("If you couldn't get it from Dao")
    void isEmpty() {
        //The setting method for mock is the same as when using normal Mockito
        when(fugaDao.selectFuga(anyInt())).thenReturn(Optional.empty());

        /*Omitted for actual validation*/

    }
}

Supplement

The following is a supplement about this method.

1 For contents that can be related to the instance contents by yourself, such as input to the constructor, it is better to directly Mock and test unless there are special circumstances.

2 It is strange that the testing of a concrete class depends on the implementation of CustomValidator, so it is better to make CustomValidator Mock. As far as I researched, I found the following method.

--Use reflection to replace Custom Validator with Mock --Use JMockito or Power Mock to "Mock all instances of that class"

In this article, I decided not to use either method due to various reasons, so I am testing with the method of converting Bean to Mock.

Related article

-[SpringBoot] Move validation (@Validated / @Valid) at any time -Qiita -[SpringBoot] Until @Autowired is run in the test class [JUnit5] -Qiita

Recommended Posts

[Spring Boot] Mock the contents that are autowired outside the scope [JUnit 5]
[Spring Boot] Until @Autowired is run in the test class [JUnit5]
Sample code that uses the Mustache template engine in Spring Boot
Spring Boot for the first time
What is @Autowired in Spring boot?
A memo that touched Spring Boot
What are the rules in JUnit?
The problem that the contents of params are completely displayed in the [Rails] view
Autowired fields in a class that inherits TextWebSocketHandler in Spring Boot become NULL