Spring 单元测试之Mock -mockito

https://blog.51cto.com/11147669/2425227
https://blog.csdn.net/u013553309/article/details/89680632

使用 mockito 写测试用例

一、引入依赖

```c
    <properties>
        <spring-verison>5.2.9.RELEASE</spring-verison>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring-verison}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring-verison}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring-verison}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>1.10.19</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

mockito推荐

        <!-- powermock增强 -->
        <!-- https://mvnrepository.com/artifact/org.powermock/powermock-module-junit4 -->
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-module-junit4</artifactId>
            <version>2.0.9</version>
            <scope>test</scope>
        </dependency>
        <!-- powermock 使用 mckito -->
        <!-- https://mvnrepository.com/artifact/org.powermock/powermock-api-mockito2 -->
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-api-mockito2</artifactId>
            <version>2.0.9</version>
            <scope>test</scope>
        </dependency>

easymock推荐

        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-module-junit4</artifactId>
            <version>2.0.9</version>
            <scope>test</scope>
        </dependency>
		<dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-api-easymock</artifactId>
            <version>2.0.9</version>
            <scope>test</scope>
        </dependency>

二、模拟

1. service模拟

模拟第三方 service

package com.lwp.demo.service;

import com.lwp.demo.BaseMockTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * Test1ServiceImplTest
 *
 * @author xxx
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value={"classpath:applicationContext.xml"})
public class Test1ServiceImplMockTest extends BaseMockTest {

    /**
     * 其他未定义 @Mock 的类,通过 spring注入到 IOC中
     */
    @Autowired
    @InjectMocks
    private Test1Service test1Service;

    //需要 mock 执行的 类
    @Mock
    private Test2Service test2Service;

    @Before
    public void init() {
        //Mock IOC
        MockitoAnnotations.initMocks(this);
    }


    @Test
    public void sayHello() {
        String name = "123";
        String responseBase = "你的名字是 ..";
        Mockito.when(test2Service.sayHello(name))
                .thenReturn(responseBase);
        System.out.println(test1Service.sayHello(name));;
    }
}

Test1Service

public interface Test1Service {

    String sayHello(String name);
}

Test1ServiceImpl

@Service
public class Test1ServiceImpl implements Test1Service {

    @Autowired
    Test2Service test2Service;

    @Override
    public String sayHello(String name) {
        System.out.println(Thread.currentThread().getStackTrace()[1]);
        System.out.println(test2Service.sayHello(name));
        return "say hello, " + name;
    }
}

Test2Service

@Service
public class Test2Service {

    public String sayHello(String name) {
        System.out.println(Thread.currentThread().getStackTrace()[1]);
        return "say hello, " + name;
    }
}

这里模拟注入 test2Service

如果有多个类可以使用基类

基类 BaseMockTest

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value={"classpath:applicationContext.xml"})
public class BaseMockTest extends BaseTest{


    //需要 mock 执行的 类
    @Mock
    protected Test2Service test2Service;

    @Before
    public void init() {
        //Mock IOC
        MockitoAnnotations.initMocks(this);
    }
}

模拟类, 参数需要一致,所以需要放到使用的方法中 Mockito.when(test2Service.sayHello(name)) .thenReturn(responseBase)

public class Test1ServiceImplTest extends BaseMockTest {

    @Autowired
    @InjectMocks
    Test1Service test1Service;


    @Test
    public void sayHello() {
        String name = "123";
        String responseBase = "你的名字是 ..";
        Mockito.when(test2Service.sayHello(name))
                .thenReturn(responseBase);
        System.out.println(applicationContext.getClass().getName());
        System.out.println(test1Service.sayHello(name));
    }
}

模拟静态类

引入依赖

        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-module-junit4</artifactId>
            <version>2.0.9</version>
            <scope>test</scope>
        </dependency>
        <!-- powermock 使用 mckito -->
        <!-- https://mvnrepository.com/artifact/org.powermock/powermock-api-mockito2 -->
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-api-mockito2</artifactId>
            <version>2.0.9</version>
            <scope>test</scope>
        </dependency>

使用powermock ,注意@RunWith(PowerMockRunner.class)

@RunWith(PowerMockRunner.class)
@PrepareForTest({ThreadUtil.class}) // 需要@RunWith(PowerMockRunner.class)
public class StaticPowerMockTest {


    @Test
    public void sayHello() {
        PowerMockito.mockStatic(ThreadUtil.class); //绕过静态类
        Mockito.when(ThreadUtil.testMock()).thenReturn("静态方法测试");//4.预设静态类返回值
        System.out.println(ThreadUtil.testMock());
    }
}

spring

package com.lwp.demo.service;

import com.lwp.demo.BaseMockTest;
import com.lwp.demo.util.ThreadUtil;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * Test1ServiceImplTest
 *
 * @author xxx
 */

@PrepareForTest({ThreadUtil.class}) // 所有需要测试的类列在此处,适用于模拟final类或有final, private, static, native方法的类
@RunWith(PowerMockRunner.class) // 单独使用
@PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)// 是spring结合使用, SpringRunner.class 是SpringJUnit4ClassRunner 子类 同 @PowerMockRunnerDelegate(SpringRunner.class)
@ContextConfiguration(value={"classpath:applicationContext.xml"})
// @PowerMockIgnore("javax.management.*") //为了解决使用powermock后,提示classloader错误
public class SpringStaticMockTest {
//public class SpringStaticMockTest extends BaseMockTest {

    @Autowired
    @InjectMocks
    Test1Service test1Service;

    //需要 mock 执行的 类
    @Mock
    protected Test2Service test2Service;

    @Before
    public void init() {
        //Mock IOC
        MockitoAnnotations.initMocks(this);
    }


    @Test
    public void sayHello() {
        PowerMockito.mockStatic(ThreadUtil.class); //绕过静态类
        Mockito.when(ThreadUtil.testMock()).thenReturn("静态方法测试");//4.预设静态类返回值

        System.out.println(ThreadUtil.testMock());

        String name = "123";
        String responseBase = "你的名字是 ..";
        Mockito.when(test2Service.sayHello(name))
                .thenReturn(responseBase);
        System.out.println(test1Service.sayHello(name));
    }
}

spring boot

同spring

@PrepareForTest({ThreadUtil.class}) // 所有需要测试的类列在此处,适用于模拟final类或有final, private, static, native方法的类
@RunWith(PowerMockRunner.class) // 单独使用
@PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)// 是spring结合使用, SpringRunner.class 是SpringJUnit4ClassRunner 子类 同 @PowerMockRunnerDelegate(SpringRunner.class)
// @PowerMockIgnore("javax.management.*") //为了解决使用powermock后,提示classloader错误
public class SpringStaticMockSpringTest extends BaseMockTest {
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值