인쇄 서비스에 대한 테스트를 작성하고 싶습니다. 나는 TestNG와 Mockito와 함께 Spring을 사용하고있다.스프링 테스트에 모의 주입하기 Mockito + Spring + TestNG
지금까지 스프링 컨텍스트와 필요한 테스트 클래스에 대한 테스트 구성 클래스를 만들었습니다.
테스트하려는 PrintingService 클래스는 여러 서비스에 따라 달라 지므로 모의하기로했습니다. 내 문제는 내가 스프링과 함께 작동시키지 못한다는 것이다. 내가 테스트를 시작 매번 봄은 예외 내 문제를 해결할 것 @InjectMocks
주석을 사용하여 생각
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)}
을 던지고,하지만하지 않았다. 어쩌면 내가 어떤 부분을 이해하지 못했을 수도 있고, 서비스 테스트에 대한 나의 생각이 완전히 틀렸을 수도 있습니다.
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();
}
}
PrintingServiceTest
@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() {
...
}
}