Spring Boot Controller 测试: mocking service requiring downstream objects causing ApplicationContext to not load

标签 spring unit-testing spring-boot jpa entitymanager

我正在尝试使用 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/

相关文章:

java - 为什么我的项目需要使用 JavaConfig 的 Spring Security 的 applicationContext.xml

java - 如何在 Spring MVC 中从 Controller 调用组件或服务

html - Spring Thymeleaf 如何使用 select 和 option html 标签在数据库中保存特定值

javascript - 在 e2e 测试中测试路由 Karma 时出错

Javascript - 测试 DOM 操作

php - 在 Symfony4 单元测试中创建多个实体

java - 数据 Jpa 测试无法加载属性

java - Spring data mongodb并发获取和更新是线程安全的吗?

java - spring boot 应用程序中的双日志文件

spring-boot - Spring Boot Actuator - 查询特定的健康指标?