实现基于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解决依赖注入

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