- Test files are not included in final jar, as the scope for test is limited to testing phase only.
- Setup: Junit - 5
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> - Using
@SpringBootTestloads the applicationContext, applicationContext may contains the Bean initialized. which actually run the application for test, which will make the bean also. And if there are any db call or api call that we be hit in real time for testing. Using@SpringBootTesttell spring boot to look for all the bean and store it in spring IOC container, similar as done usingSpringBootApplication. - Parametrised test: Instead of CsvSource we can also use
@ValueSource, also we have@ArgumentSourceAlso, instead of parameters we can also use file path as well.@ParameterizedTest @CsvSource({ "1, 1, 2", "3, 5, 8" }) void testSum(int a, int b, int expected) { assertEquals(expected, a+ b); }
- We can also use
@Autowiredto inject bean with@SpringBootTest, as@SpringBootTestwill ask spring to create and collect bean at IOC container. Using this will take time, as all the bean and db connections to be made actually real. - To avoid using actual service/db/dependency we can simply mock it using
@Mock, and Inject these mock to actual place/variables using@InjectMocks. MockBeanvs@Mock: https://medium.com/@ykods/difference-between-mock-and-mockbean-in-spring-testing-9576eb312cdb- @Mock : Used when we do not involve using actual Spring Context, used with
@ExtendWithor@RunWith, used in Unit Testing. - @MockBean: It adds the Mock Bean to the Spring Boot Context, hence you can reuse this bean later using
@Autowiredor@Inject. Mostly used with@SpringBootTest. Used in IntegrationTesting
- @Mock : Used when we do not involve using actual Spring Context, used with
- Below:
This is run before each test - will initialize and inject the mocks.
@BeforeEach void setUp() { MockitoAnnotations.initMocks(this); } - When to use what ?
- In the cases when we need to mock few things and some the dependencies should not be mocked. In this case we would use Spring Context (
@SpringBootTest)
- In the cases when we need to mock few things and some the dependencies should not be mocked. In this case we would use Spring Context (