春季测试不满意的依赖NoSuchBeanDefinitionException

时间:2020-03-14 14:28:23

标签: spring spring-mvc spring-test

当我尝试运行测试时,它们都失败了,因为它们找不到我的一个类的bean。

以下是我在上下文中使用的代码:

我得到的例外是:

Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'testProtoAdminController' : Unsatisfied dependency expressed through constructor parameter 2; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'TestProtoCopyService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

TestProtoAdminControllerTest

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = TestProtoAdminController.class)
public class TestProtoAdminControllerTest {

//Some used services

 @Before
public void setUp() {
    authenticatedMockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}

@Test
@WithMockUser
public void testCopyProto() throws Exception {
    authenticatedMockMvc.perform(post("/api/admin/{id}/copy", 1)
            .contentType(MediaType.APPLICATION_JSON)
            .content(asJson(new TestProtoBaseVo()))).andExpect(status().isOk());
}

//Some more tests which are not important in this case

TestProtoCopyService

@Service
public class TestProtoCopyServiceImpl implements TestProtoCopyService {

    //Other services and repositories I have to use.
    //Methods

}

TestProtoCopyService

public interface TestProtoCopyService {
    @Transactional
    void copyTestProto(long testProtoId, String sourceTenant, String targetTenant);
}

TestProtoAdminController

@RestController
@RequestMapping("/*")
public class TestProtoAdminController {
private TestProtoCopyService testProtoCopyService;

public TestProtoAdminController(TestProtoCopyService testProtoCopyService {
    this.testProtoCopyService = testProtoCopyService;
}

1 个答案:

答案 0 :(得分:0)

使用@WebMvcTest时,Spring将准备一切以测试您的Web层。这并不意味着您的所有bean都已被扫描,并且属于此测试应用程序上下文的一部分,并且随时可以注入。

通常,通常使用@MockBean模拟控制器的服务类,然后使用Mockito来指定其行为:

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = TestProtoAdminController.class)
public class TestProtoAdminControllerTest {

  @MockBean
  private TestProtoCopyService mockedService

  // the rest

  @Before
  public void setUp() {
    authenticatedMockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
  }

  @Test
  @WithMockUser
  public void testCopyProto() throws Exception {

    authenticatedMockMvc.perform(post("/api/admin/{id}/copy", 1)
            .contentType(MediaType.APPLICATION_JSON)
            .content(asJson(new TestProtoBaseVo()))).andExpect(status().isOk());
  }

如果您希望Spring Boot用每个bean引导整个应用程序上下文,请考虑使用@SpringBootTest。使用此批注,您可以将任何bean注入您的应用程序。缺点是您需要提供整个基础架构(数据库/队列/等)以进行测试。