2017-03-29 23 views
0

印刷サービスのテストを書いてみたい。私はTestNGとMockitoでSpringを使用しています。Mockito + Spring + TestNGにモックを注入する

これまでのところ、私はSpringのコンテキストと必要なテストクラス用のテスト構成クラスを作成しました。

私がテストしたいPrintingServiceクラスはいくつかのサービスに依存しているので、私はそれらをモックすることに決めました。私の問題は、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(); 
    } 

} 

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() { 
    ... 
    } 

} 

答えて

0

あなたは@MockBeanアノテーションでモックのSpring Beanを作成することができます。 Springでテスト中のものを見ることはできませんが、単体テストを単純に保つためにコンストラクタを開いておく必要があります。つまりコンストラクタDIは、モックやその他の実装をインジェクトするためにバネに直接接続されていません。

もっと詳しい/大テストの場合@MockBeanが便利です。

関連する問題