2016-11-09 150 views
0

私はMockitoを使用して、このJUnitテストを持っている(Java用のオープンソースのテストフレームワークは、MITライセンスの下でリリース)春のWebモデル・ビュー・コントローラ(MVC)フレームワークアプリケーションでMockito:@Autowiredと@Mock

を組み合わせます

私はこのテストを持っている:

@RunWith(MockitoJUnitRunner.class) 
public class DeviceCatalogueControllerTest { 


    @InjectMocks 
    private DeviceCatalogueController controller; 

    @InjectMocks 
    protected SessionHelper sessionHelper; 

    @Mock 
    private MessageSource messageSource; 

    @Mock 
    protected CataloqueService cataloqueService; 

    @Autowired 
    protected ApplicationDao applicationDao; 

    @Before 
    public void setUpTest() { 
     request = new MockHttpServletRequest(); 
     response = new MockHttpServletResponse(); 
    } 

    @Test 
    public void testInitFormGet() throws Exception { 

     System.out.println ("SessionHelper sessionHelper --> " + sessionHelper); 

     //controller.initFormGet(searchForm, localeParam, request, response, model, locale) 
     controller.initFormGet(null, DEFAULT_LOCALE, request, response, null, new Locale(DEFAULT_LOCALE)); 
     } 

が、テストを実行するときにapplicationDaoは、あなたのテストクラスがSpringの全く気付いていないヌル

+0

「ヌル」ではないのはなぜですか? –

答えて

1

です。ユニットテストでSpringを使用するには、現在使用している@RunWith(MockitoJUnitRunner.class)ではなく、正確な注釈@RunWith(SpringJUnit4ClassRunner.class)を使用する必要があります。

@ContextConfiguration(locations = {"classpath:/application-context.xml"}) 
@RunWith(SpringJUnit4ClassRunner.class) 
public class DeviceCatalogueControllerTest { 


    @InjectMocks 
    private DeviceCatalogueController controller; 

    @InjectMocks 
    protected SessionHelper sessionHelper; 

    @Mock 
    private MessageSource messageSource; 

    @Mock 
    protected CataloqueService cataloqueService; 

    @Autowired 
    protected ApplicationDao applicationDao; 

    @Before 
    public void setUpTest() { 
     MockitoAnnotations.initMocks(this); 
     request = new MockHttpServletRequest(); 
     response = new MockHttpServletResponse(); 
    } 

    @Test 
    public void testInitFormGet() throws Exception { 

     System.out.println("SessionHelper sessionHelper --> " + sessionHelper); 

     //controller.initFormGet(searchForm, localeParam, request, response, model, locale) 
     controller.initFormGet(null, DEFAULT_LOCALE, request, response, null, new Locale(DEFAULT_LOCALE)); 
    } 
} 

注:であなたのapplication-context.xmlの正しいXMLパスを使用し

次に@Before方法であなたは、あなたのテストクラスとして再符号化することができるMockitoAnnotations.initMocks(this);

を呼び出すことによって、あなたのMockitoモックを初期化することができます@ContextConfiguration(locations = {"classpath:/application-context.xml"})