Convert Bean
to Mock
to test the content involving Custom Validator
such as using @ Autowired
.
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*/
}
}
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
.
-[SpringBoot] Move validation (@Validated / @Valid) at any time -Qiita -[SpringBoot] Until @Autowired is run in the test class [JUnit5] -Qiita
Recommended Posts