类、接口和枚举准备
public interface Person {
String getName();
}
public enum PersonType {
S("student"), N("normal");
private String type;
PersonType(String type) {
this.type = type;
}
public String getType(){
return type;
}
}
public class Student implements Person {
private int age;
public Student(){
}
public Student(int age){
this.age = age;
}
public int getAge(){
return this.age;
}
public static String getStaticMethod() {
return "staticMethod";
}
public String getName() {
return "student";
}
public final String getFinalMethod(){
return "getFinalMethod";
}
private String getPrivateMethod(){
return "getPrivateMethod";
}
public String callPrivateMethod(){
return getPrivateMethod();
}
}
mockito测试
package mockitoNormal.personcase;
import org.junit.Test;
import org.mockito.Mockito;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class PersonNormalTest {
//Mock Interface,这是正常的Mock,mock()函数可以调用mockito的,也可以调用powermock的。
@Test
public void testMockInterface() {
Person person = mock(Person.class);
String mockPersonGetName = "mockPersonGetName";
when(person.getName()).thenReturn(mockPersonGetName);
assertThat(person.getName(), is(mockPersonGetName));
}
//Mock Normal Class, 这也是正常的mock, 可以使用mockito或者是powermock的mock方法
@Test
public void testMockNormalMethod() {
Student student = mock(Student.class);
String mockStudentGetName = "mockStudentGetName";
when(student.getName()).thenReturn(mockStudentGetName);
assertThat(student.getName(), is(mockStudentGetName));
}
}
依赖
org.mockito
mockito-core
2.8.47
junit
junit
4.11
powermockito测试
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.api.support.membermodification.MemberMatcher;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.when;
@RunWith(PowerMockRunner.class)
@PrepareForTest({Student.class,PersonType.class})
public class PowerTest {
//Mock Final Class,这种Mock就必须使用powermock了,而且使用powermock,需要在测试类上面加两个注解。
// @PrepareForTest里面的类,就是你要mock的方法所在的类
@Test
public void testMockFinalMethod() {
Student student = PowerMockito.mock(Student.class);
String mockFinalMethod = "mockFinalMethod";
when(student.getFinalMethod()).thenReturn(mockFinalMethod);
assertThat(student.getFinalMethod(), is(mockFinalMethod));
}
//Mock Private Method,这种Mock也必须使用powermock,我在下面演示的代码使用了spy, 这是因为spy是之后是部分mock,
// 这里我只想mock getPrivateMethod(), 而不想Mock callPrivateMethod。但是mock是会把类里面的所有的方法都重新构造,
// 这样就达不到测试private method的目的了。
@Test
public void testMockPrivateMethod() throws Exception {
Student student = PowerMockito.spy(new Student());
String mockPrivateMethod = "mockPrivateMethod";
PowerMockito.when(student, "getPrivateMethod").thenReturn(mockPrivateMethod);
assertThat(student.callPrivateMethod(), is(mockPrivateMethod));
}
@Test
public void testMockPrivateMethodWithStub() throws Exception {
Student student = new Student();
String mockPrivateMethod = "mockPrivateMethod";
PowerMockito.stub(MemberMatcher.method(Student.class, "getPrivateMethod")).toReturn(mockPrivateMethod);
assertThat(student.callPrivateMethod(), is(mockPrivateMethod));
}
//Mock Static Method,这种方式也必须使用powermock.
@Test
public void testMockStaticMethod(){
mockStatic(Student.class);
String mockStaticMethod = "mockStaticMethod";
when(Student.getStaticMethod()).thenReturn(mockStaticMethod);
assertThat(Student.getStaticMethod(), is(mockStaticMethod));
}
//6.Mock Constructor,这种方式也需要依赖powermock.
@Test
public void testMockConstructMethod() throws Exception {
Student student1000 = new Student(1000);
PowerMockito.whenNew(Student.class).withArguments(10).thenReturn(student1000);
Student student10 = new Student(10);
assertThat(student10.getAge(), is(1000));
}
//Mock Enum,这种方式也需要依赖powermock
@Test
public void testMockEnum(){
PersonType personType = PowerMockito.mock(PersonType.class);
Whitebox.setInternalState(PersonType.class, "N", personType);
when(personType.getType()).thenReturn("mockN");
assertThat(PersonType.N.getType(), is("mockN"));
assertThat(PersonType.S.getType(), is("student"));
}
}
依赖
junit
junit
4.11
org.powermock
powermock-module-junit4
1.7.4
org.powermock
powermock-api-mockito
1.7.4
附加list对象测试和mockito对象的三种方式
import org.junit.Test;
import java.util.LinkedList;
import static org.mockito.Mockito.*;
public class MockListTest {
//模拟LinkedList 的对象
@Test
public void mockEntity(){
// 模拟LinkedList 的对象
LinkedList mockedList = mock(LinkedList.class);
// 模拟获取第一个元素时,返回字符串first
when(mockedList.get( 0 )).thenReturn( "first" );
// 此时打印输出first
System.out.println(mockedList.get( 0 ));
}
//模拟方法调用抛出异常
@Test
public void mockEntity2(){
// 模拟LinkedList 的对象
LinkedList mockedList = mock(LinkedList.class);
// 模拟获取第二个元素时,抛出RuntimeException
when(mockedList.get( 1 )).thenThrow( new RuntimeException());
// 此时将会抛出RuntimeException
System.out.println(mockedList.get( 1 ));
}
@Test
public void mockEntity3(){
// 模拟LinkedList 的对象
LinkedList mockedList = mock(LinkedList.class);
doThrow(new RuntimeException()).when(mockedList).clear();
}
//模拟方法调用的参数匹配
@Test
public void mockEntity4(){
// 模拟LinkedList 的对象
LinkedList mockedList = mock(LinkedList.class);
// anyInt()匹配任何int参数,这意味着参数为任意值,其返回值均是element
when(mockedList.get(anyInt())).thenReturn("element");
// 此时打印是element
System.out.println(mockedList.get(999));
}
//验证方法调用次数
@Test
public void mockEntity5(){
// 模拟LinkedList 的对象
LinkedList mockedList = mock(LinkedList.class);
// 调用add一次
mockedList.add("once");
// 下面两个写法验证效果一样,均验证add方法是否被调用了一次
verify(mockedList).add("once");
verify(mockedList, times(2)).add("once");;
}
}
package threemethod;
public interface IBaseUserMainService {
}
package threemethod;
import org.junit.Before;
import org.mockito.Mockito;
public class LoginInfoActionTest {
private IBaseUserMainService baseUserMainService;
@Before
void init() {
baseUserMainService = Mockito.mock(IBaseUserMainService.class);
}
}
package threemethod;
import org.junit.Before;
import org.mockito.Mockito;
import static org.mockito.Mockito.mock;
public class LoginInfoActionTest2 {
private IBaseUserMainService baseUserMainService;
@Before
void init() {
baseUserMainService = mock(IBaseUserMainService.class);
}
}
package threemethod;
import org.junit.Before;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import static org.mockito.Mockito.mock;
import static org.mockito.MockitoAnnotations.*;
public class LoginInfoActionTest3 {
private @Mock
IBaseUserMainService baseUserMainService;
@Before
void init() {
MockitoAnnotations.initMocks(this);
}
}
package threemethod;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class LoginInfoActionTest4 {
private @Mock IBaseUserMainService baseUserMainService;
@Before
void init() {
}
}
部分mock
class Jerry {
public void goHome() {
doSomeThingA();
doSomeThingB();
}
// real invoke it.
public void doSomeThingB() {
System.out.println("good day");
}
// auto mock method by mockito
public void doSomeThingA() {
System.out.println("you should not see this message.");
doSomeThingB();
}
public boolean go() {
System.out.println("I say go go go!!");
return true;
}
// 当需要整体Mock,只有少部分方法执行真正部分时,选用这种方式
@Test
public void callRealMethodTest() {
Jerry jerry = Mockito.mock(Jerry.class);
Mockito.doCallRealMethod().when(jerry).goHome();
Mockito.doCallRealMethod().when(jerry).doSomeThingB();
jerry.goHome();
Mockito.verify(jerry,Mockito.times(1)).doSomeThingA();
Mockito.verify(jerry,Mockito.times(1)).doSomeThingB();
}
// 当需要整体执行真正部分,只有少部分方法执行mock,选用这种方式
@Test
public void spyTest() {
Jerry spyJack = Mockito.spy(new Jerry());
// 用thenReturn 会走go()方法体,然后将返回值Mock掉
Mockito.when(spyJack.go()).thenReturn(false);
Assert.assertFalse(spyJack.go());
// 用doReturn 不走go()方法体
Mockito.doReturn(false).when(spyJack).go();
Assert.assertFalse(spyJack.go());
}