Mockito之:Spy
被测试方法
package com.newcrud.learn;
import lombok.Data;
@Data
public class MySpy {
int a=100;
public void fun(){
System.out.println("fun");
funOne();
funTwo();
}
public void funOne(){
System.out.println("funOne");
}
public void funTwo(){
System.out.println("funTwo");
}
public Integer getMath(){
return a;
}
}
测试类
package com.newcrud.learn;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.mockito.Mockito.when;
import static org.testng.Assert.*;
@SpringBootTest
public class MySpyTest extends AbstractTestNGSpringContextTests {
@Spy
MySpy mySpy;
@BeforeClass
public void initMocks(){
MockitoAnnotations.initMocks(this);
}
@Test
public void testFun() {
mySpy.fun();
System.out.println("=======");
}
@Test
public void testFunOne() {
mySpy.funOne();
System.out.println("=======");
}
@Test
public void testFunTwo() {
mySpy.funTwo();
System.out.println("=======");
}
@Test
public void testGetMath() {
System.out.println(mySpy.getMath());
}
@Test
public void testGetMathTwo(){
when(mySpy.getMath()).thenReturn(200);
System.out.println(mySpy.getMath());
}
}
结果
fun
funOne
funTwo
=======
funOne
=======
funTwo
=======
100
200
结论
1、Mock声明的对象,对函数的调用均执行mock(即虚假函数),不执行真正部分。
2、Spy声明的对象,对函数的调用均执行真正部分。
3、相对于@Mock(answer = Answers.CALLS_REAL_METHODS),更推荐@Spy