我正在使用@WebMvcTest来测试控制器。我观察到需要在测试类的SpringBoot应用程序类中模拟自动装配的bean。根据我的理解,使用@WebMvcTest可以独立测试控制器。只是想知道为什么我需要模拟SpringBootApplication类中使用的EmployeeService。以下是相关的类-
@RunWith(SpringRunner.class)
@WebMvcTest(EmployeeController.class)
public class EmployeeControllerTest {
@Autowired
MockMvc mockMvc;
@MockBean
EmployeeService employeeService;
@Test
public void getEmployee() throws Exception {
mockMvc.perform(get("/employee")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
}
SpringBootApplication类
@SpringBootApplication
public class DemoApplication {
@Autowired
EmployeeService employeeService;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
EmployeeController
@RestController
public class EmployeeController {
@GetMapping(value = "/employee")
public Employee getEmployee() {
return Employee.builder().
name("Harry")
.id("1")
.build();
}
}
雇员豆
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class Employee {
private String id;
private String name;
}
我正在使用SpringBoot版本2.1.6