Spring 测试未满足的依赖项 NoSuchBeanDefinitionException

Spring Testing Unsatisfied depencency NoSuchBeanDefinitionException

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

之一的 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;
}

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

一般来说,您通常使用 @MockBean 模拟控制器的服务 class,然后使用 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 引导到每个 bean 的整个应用程序上下文 bootstrap,请考虑使用 @SpringBootTest。使用此注释,您可以将任何 bean 注入到您的应用程序中。这里的缺点是您需要为您的测试提供整个基础设施 (database/queues/etc.)。