【发布时间】:2021-07-21 23:41:36
【问题描述】:
我有一个 Spring Boot 应用程序,它具有一个控制器类、一个服务和一个存储库,运行良好。我已经为此添加了 Junit 测试用例,而且效果也很好。
@RestController
public class EmployeeController{
@Autowired
EmployeeService service;
@GetMapping("/list")
public List<Employee> getEmployee(){
return service.findAll();
}
}
@Service
public class EmployeeService{
@Autowired
EmployeeRepository repository;
public List<Employee> findAll(){
return repository.findAll();
}
}
@Repository
public interface EmployeeRepository extends JpaRepository<Employee, String>{}
测试类如下。
@RunWith(SpringRunner.class)
@WebMvcTest(value = EmployeeController.class)
class EmployeeControllerIntegrationTest {
@Autowired
private MockMvc mvc;
@MockBean
private EmployeeService service;
@Test
public void findAllEmployeeTest(){
}
}
测试用例一直通过,但目前我正在添加另一个 API,因为下面所有测试都失败了。
@RestController
public class DepartmentController{
@Autowired
DepartmentService service;
@GetMapping("/list")
public List<Department> getDepartment(){
return service.findAll();
}
}
@Service
public class DepartmentService{
@Autowired
DepartmentRepository repository;
public List<Department> findAll(){
return repository.findAll();
}
}
@Repository
public interface DepartmentRepository extends JpaRepository<Department, String>{}
测试类如下。
@RunWith(SpringRunner.class)
@WebMvcTest(value = DepartmentController.class)
class DepartmentControllerIntegrationTest {
@Autowired
private MockMvc mvc;
@MockBean
private DepartmentService service;
@Test
public void findAllDepartmentTest(){
}
}
添加部门服务测试用例后失败并出现以下错误:
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'departmentController': Unsatisfied dependency expressed through field 'departmentService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'departmentService': Unsatisfied dependency expressed through field 'repository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.employeeapp.data.repository.DepartmentRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
干杯!
【问题讨论】:
标签: java spring-boot junit integration-testing rest