有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将模拟注入Spring测试Mockito+Spring+TestNG

我想为打印服务写一个测试。我将Spring与TestNG和Mockito一起使用

到目前为止,我已经为我的spring上下文和所需的测试类创建了一个测试配置类

我想测试的PrintingService类依赖于几个服务,所以我决定模拟它们。我的问题是,我无法让它与Spring一起工作。每次我开始测试时,spring都会抛出一个异常

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.printservice.server.message.MessageService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

我原以为使用@InjectMocks注释可以解决我的问题,但事实并非如此。也许我对某些方面理解错误,或者我测试服务的想法完全错误

PrintingTestConfig

package com.example.printservice;

import com.example.printservice.server.print.PrintingService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

@Configuration
@ComponentScan(basePackageClasses = {PrintingService.class}, scopedProxy = ScopedProxyMode.TARGET_CLASS)
public class PrintingTestConfig {

  @Bean
  public static PropertySourcesPlaceholderConfigurer propertyConfigIn() {
    return new PropertySourcesPlaceholderConfigurer();
  }

}

打印服务测试

@ContextConfiguration(classes = PrintingTestConfig.class, loader = AnnotationConfigContextLoader.class)
public class PrintingServiceTest extends AbstractTestNGSpringContextTests {

  @Mock
  private MessageService _messageService;

  @Mock
  private ClientCache_clientCache;

  @Mock
  private PrinterCache _printerCache;

  @Value("classpath:example.pdf")
  private Resource _examplePdf;

  @InjectMocks
  private PrintingService _printingService;

  @BeforeMethod
  public void setup() {
    MockitoAnnotations.initMocks(this);
  }

  @Test
  public void printPdf() {
    ...
  }

}

共 (1) 个答案

  1. # 1 楼答案

    可以使用@MockBean注释创建模拟Springbean。虽然我看不到Spring测试的内容,但您应该打开构造函数,以保持单元测试的简单性,即构造函数DI,这样它就不会直接绑定到Spring来注入模拟或其他实现

    在更详细/大型测试的情况下@MockBean是有用的