Am developing MicroServices in springBoot. Am writing unit test for Service and DAO layer. When I use @SpringBootTest it starting application on build. But It should not start application when I run unit test. I used @RunWith(SpringRunner.class), But am unable to @Autowired class instance in junit class. How can I configure junit test class that should not start application and how to @Autowired class instance in junit class.
Use MockitoJUnitRunner for JUnit5 testing if you don't want to start complete application.
Any Service, Repository and Interface can be mocked by @Mock annotation.
@InjectMocks is used over the object of Class that needs to be tested.
Here's an example to this.
@RunWith(MockitoJUnitRunner.class)
@SpringBootTest
public class AServiceTest {
@InjectMocks
AService aService;
@Mock
ARepository aRepository;
@Mock
UserService userService;
@Before
public void setUp() {
// MockitoAnnotations.initMocks(this);
// anything needs to be done before each test.
}
@Test
public void loginTest() {
Mockito.when(aRepository.findByUsername(ArgumentMatchers.anyString())).thenReturn(Optional.empty());
String result = aService.login("test");
assertEquals("false", result);
}