我正在尝试使用 Mock 来运行 Controller 级 Spring Boot 单元测试来实现我的服务层依赖项。但是,此模拟需要使用 EntityManager
对象的下游存储库依赖项,这导致我的测试在加载 ApplicationContext
时失败。
我的测试不涉及存储库依赖项或EntityManager
,它使用模拟服务对象返回预设响应。如果我只想模拟服务层对象,为什么 Spring 会提示 repo/EntityManager
?
Controller 单元测试代码:
@RunWith(SpringRunner.class)
@WebMvcTest
@AutoConfigureWebClient
public class MobileWearControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
UserDeviceService userDeviceService;
//.....
}
UserDeviceService代码:
@Service
public class UserDeviceService {
private UserDeviceRepository userDeviceRepository;
public UserDeviceService(UserDeviceRepository userDeviceRepository) {
this.userDeviceRepository = userDeviceRepository;
}
//....
}
UserDeviceRepository 代码:
@Repository
public class UserDeviceRepositoryImpl implements UserDeviceRepositoryCustom {
@PersistenceContext
private EntityManager em;
//....
}
期待测试运行。
实际结果是获取以下堆栈跟踪:
java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDeviceRepositoryImpl': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.persistence.EntityManagerFactory' available
...
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.persistence.EntityManagerFactory' available
...
最佳答案
我的问题是我用于测试的注释。
使用@AutoConfigureWebClient尝试支持整个Spring上下文;因为我正在对我的 Controller 进行单元测试,所以我只想测试 Web 层并模拟下游依赖项(即 UserDeviceService)。因此,我应该改用 @SpringBootTest 和 @AutoConfigureMockMvc,这将为 Controller 层设置 Spring 上下文。
使用这种方法,我能够成功模拟 UserDeviceService,从而允许我的测试编译和运行:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class MobileWearControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
UserDeviceService userDeviceService;
//...
}
关于Spring Boot Controller 测试: mocking service requiring downstream objects causing ApplicationContext to not load,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55716715/