相同点

spy和mock生成的对象不受spring管理

不同点

1.默认行为不同

对于未指定mock的方法,spy默认会调用真实的方法,有返回值的返回真实的返回值,而mock默认不执行,有返回值的,默认返回null

2.使用方式不同

Spy中用when...thenReturn私有方法总是被执行,预期是私有方法不应该执行,因为很有可能私有方法就会依赖真实的环境
Spy中用doReturn..when才会不执行真实的方法。

mock中用 when...thenReturn 私有方法不会执行

3.代码统计覆盖率不同
@spy使用的真实的对象实例,调用的都是真实的方法,所以通过这种方式进行测试,在进行sonar覆盖率统计时统计出来是有覆盖率;
@mock出来的对象可能已经发生了变化,调用的方法都不是真实的,在进行sonar覆盖率统计时统计出来的Calculator类覆盖率为0.00%。

以下为测试代码部分


 

Calculator.java
class Calculator {
    private int sumXX(int a, int b) {
        System.out.println("sumXX");
        return a + b;
    }

    public int callSumXX(int a, int b) {
        System.out.println("callSumXX");
        return  sumXX(a, b);
    }
}
SpyAndMockTest.java
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.anyInt;

@RunWith(PowerMockRunner.class)
@PrepareForTest({Calculator.class})
public class SpyAndMockTest {
   
    @Test
    public void testSumXXBySpy_Call_Private_Method() throws Exception {
        Calculator cal= PowerMockito.spy(new Calculator());
        PowerMockito.when(cal,"sumXX",anyInt(),anyInt()).thenReturn(2);
        assertEquals(2, cal.callSumXX(1, 2));
    }

   
    @Test
    public void testSumXXBySpy_Not_Call_Private_Method() throws Exception {
        Calculator cal= PowerMockito.spy(new Calculator());
        PowerMockito.doReturn(2).when(cal,"sumXX",anyInt(),anyInt());
        assertEquals(2, cal.callSumXX(1, 2));
    }

    @Test
    public void testSumXXByMock_Not_Call_Real_Method() throws Exception {
        Calculator cal= PowerMockito.mock(Calculator.class);
        PowerMockito.when(cal,"sumXX",anyInt(),anyInt()).thenReturn(2);
        assertEquals(0, cal.callSumXX(1, 2));
    }
    @Test
    public void testSumXXByMock_Call_Real_Method() throws Exception {
        Calculator cal= PowerMockito.mock(Calculator.class);
        PowerMockito.when(cal,"sumXX",anyInt(),anyInt()).thenReturn(2);
        PowerMockito.when(cal.callSumXX(anyInt(),anyInt())).thenCallRealMethod();//指明callSumXX调用真实的方法
        assertEquals(2, cal.callSumXX(1, 2));
    }
}

附上 pom.xm文件依赖

      <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-api-mockito2</artifactId>
            <version>2.0.0-beta.5</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-core</artifactId>
            <version>2.0.0-beta.5</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.powermock</groupId>
            <artifactId>powermock-module-junit4</artifactId>
            <version>2.0.0-beta.5</version>
            <scope>test</scope>
        </dependency>

  

01-15 03:31