Inside a project, I have a service A that uses beans B1 and B2. If I want to create an integration test for the service A, I usually create the test class like this:
@SpringBootTest(classes = {A.class, B1.class, B2.class})
@ActiveProfiles("test")
class AIntegrationTest {
...
}
My question: is this approach fine or is there a clean solution?
CodePudding user response:
Here's another example from the spring docs.
package com.example.testingweb;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class HttpRequestTest {
@LocalServerPort
private int port;
@Autowired
private TestRestTemplate restTemplate;
@Test
public void greetingShouldReturnDefaultMessage() throws Exception {
assertThat(this.restTemplate.getForObject("http://localhost:" port "/",
String.class)).contains("Hello, World");
}
}
CodePudding user response:
Not sure you even need to define the beans in the @SpringBootTest annotation. either @Mock the classes with mockito to @Autowire them
// here's an example from the web
@RunWith(SpringRunner.class)
@SpringBootTest(
SpringBootTest.WebEnvironment.MOCK,
classes = Application.class)
@AutoConfigureMockMvc
@TestPropertySource(
locations = "classpath:application-integrationtest.properties")
public class EmployeeRestControllerIntegrationTest {
@Autowired
private MockMvc mvc;
@Autowired
private EmployeeRepository repository;
// write test cases here
}