Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write Unit test in SpringBoot Without start application

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.

like image 290
user3410249 Avatar asked Sep 08 '26 19:09

user3410249


2 Answers

With Spring Boot you can start a sliced version of your application for your tests. This will create a Spring Context that only contains a subset of your beans that are relevant e.g. only for your web layer (controllers, filters, converters, etc.): @WebMvcTest.

There is a similar annotation that can help you test your DAOs as it only populates JPA and database relevant beans (e.g. EntitiyManager, Datasource, etc.): @DataJpaTest.

If you want to autowire a bean that is not part of the Spring Test Context that gets created by the annotatiosn above, you can use a @TestConfiguration to manually add any beans you like to the test context

@WebMvcTest(PublicController.class)
class PublicControllerTest {

  @Autowired
  private MockMvc mockMvc;

  @TestConfiguration
  static class TestConfig {

    @Bean
    public EntityManager entityManager() {
      return mock(EntityManager.class);
    }

    @Bean
    public MeterRegistry meterRegistry() {
      return new SimpleMeterRegistry();
    }

  }
}
like image 126
rieckpil Avatar answered Sep 10 '26 10:09

rieckpil


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);
    }
like image 43
Nakul Goyal Avatar answered Sep 10 '26 10:09

Nakul Goyal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!