實現基於spring+mockito的跨多層接口的mock測試

概述

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

使用簡介

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

代碼示例

  • ServiceA.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class ServiceA {
    @Autowired
    private ServiceB serviceB;
    public String test(){
        return serviceB.test();
    }
}

  • ServiceB.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class ServiceB {
    @Autowired
    private ServiceC serviceC;
    public String test(){
        return serviceC.test();
    }
}

  • ServiceC.java
import org.springframework.stereotype.Service;

/**
 * @author Liam
 * @version 1.0 2020/4/27
 */
@Service
public class ServiceC {
    public String test() {
        return "ServiceC test";
    }
}

  • mock測試代碼
    普通使用InjectMock與Mock註解的方式,發現只能在A調用B的情況下,把B mock掉.但是當B調用C時,只mock掉C就會發現,C無法直接inject到A內,下面的方式可以實現A調用B,B調用C,只mock掉C的情況.
import org.junit.Before;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.util.ReflectionTestUtils;


@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class Test {
    @Autowired
    private ServiceA serviceA;
    @Autowired
    private ServiceB serviceB;
    @Autowired
    private ServiceC serviceC;

    @Before
    public void setup() {
        serviceC = Mockito.mock(ServiceC.class);
        //通過反射修改serviceB下面的serviceC私有屬性
        ReflectionTestUtils.setField(serviceB, "serviceC", serviceC);
    }

    @org.junit.Test
    public void testService() {
    	//模擬返回值,調用serviceC.test()方法時直接return "test aaa"
        Mockito.when(serviceC.test()).thenReturn("test aaa");
        System.out.println(serviceA.test());
    }
}

  • pom.xml依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>
   

參考

1. 關於如何實現基於spring+mockito的跨多層接口的mock測試
2. 使用ReflectionTestUtils解決依賴注入

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章