使用ReflectionTestUtils解決依賴注入


概述

當使用junit來測試Spring的代碼時,為了減少依賴,需要給對象的依賴,設置一個mock對象,但是由於Spring可以使用@Autoware類似的注解方式,對私有的成員進行賦值,此時無法直接對私有的依賴設置mock對象。可以通過引入ReflectionTestUtils,解決依賴注入的問題。

使用簡介

在Spring框架中,可以使用注解的方式如:@Autowair、@Inject、@Resource,對私有的方法或屬性進行注解賦值,如果需要修改賦值,可以使用ReflectionTestUtils達到目的。

代碼例子

待測試類:Foo

package com.github.yongzhizhan.draftbox.springtest;

import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * 被測類
 */
public class Foo {
    @Autowired
    private String m_String;

    @PostConstruct
    private void onStarted(){
        System.out.println("on started " + m_String);
    }

    @PreDestroy
    private void onStop(){
        System.out.println("on stop " + m_String);
    }
}

使用ReflectionTestUtils解決依賴注入:

package com.github.yongzhizhan.draftbox.springtest;

import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;

/**
 * 使用ReflectionTestUtils解決依賴注入
 * @author zhanyongzhi
 */
public class ReflectionTestUtilsTest {
    @Test
    public void testDefault(){
        Foo tFoo = new Foo();

        //set private property
        ReflectionTestUtils.setField(tFoo, "m_String", "Hello");

        //invoke construct and destroy method
        ReflectionTestUtils.invokeMethod(tFoo, "onStarted");
        ReflectionTestUtils.invokeMethod(tFoo, "onStop");
    }
}

在github中查看

參考

unit-testing


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM