使用Spring Boot执行@WebMvcTest时,是否有办法获取注入自定义bean验证器中的EntityManager实例?

问题描述

我创建了一个自定义bean验证器,如下所示:

public class UniqueValidator implements ConstraintValidator<Unique,Object> {

    private final EntityManager entityManager;
    private Class<?> entityClass;
    private String entityField;

    public UniqueValidator(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    public void initialize(Unique constraint) {
        entityClass = constraint.entityClass();
        entityField = constraint.entityField();
    }

    public boolean isValid(Object value,ConstraintValidatorContext context) {
        return !ExistsValidation.exists(entityManager,entityClass,entityField,value);
    }

}

它工作得很好,但是当我在测试上下文中命中端点时,EntityManager不会被注入并抛出异常:Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'javax.persistence.EntityManager' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

那是我要开始工作的测试:

@WebMvcTest(ProposalController.class)
class ProposalControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private ObjectMapper objectMapper;

    @MockBean
    private ProposalRepository proposalRepository;

    @Test
    public void testCreateProposal() throws Exception {
        // given
        var request = new ProposalRequest(
                "Tânia","Bárbara Mendes","159.296.683-70","[email protected]",LocalDate.of(2000,12,9));
        ArgumentCaptor<Proposal> captor = ArgumentCaptor.forClass(Proposal.class);

        // when
        MockHttpServletResponse response = mockMvc.perform(
                post("/proposals").contentType(MediaType.APPLICATION_JSON)
                        .content(objectMapper.writeValueAsString(request)))
                .andReturn().getResponse();

        // then
        verify(proposalRepository,times(1)).save(captor.capture());

        assertThat(captor.getValue()).isEqualToComparingFieldByField(request.toProposal());
        assertThat(response.getStatus()).isEqualTo(CREATED.value());
    }
}

在执行上述测试方案时,如何将EntityManager注入到自定义bean验证程序中?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)