Mockito应用


import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;

public class MockitoDemo {
@Test
public void mockitoTest() throws Exception {
Service service = new Service();
Dao dao = mock(Dao.class);// 相当于 new一个dao的模拟类
service.setDao(dao);
when(dao.update("1", "2")).thenReturn(2);
Assert.assertEquals(2, service.update("1", "2"));

// 方法的参数可以匹配任意值,Mockito.anyXXX() 和任意类 Mockito.any(clazz)
when(dao.update(Mockito.anyString(), Mockito.any(String.class))).thenReturn(3);
// 不能将确定值和模糊值混搭,这样会报错
// when(dao.update("3", Mockito.any(String.class))).thenReturn(3);
Assert.assertEquals(3, service.update("3", "4"));

// 下面模拟抛异常
when(dao.update("3", "4")).thenThrow(new RuntimeException());
Assert.assertEquals(-1, service.update("3", "4"));

// void方法抛异常
Mockito.doThrow(new RuntimeException("测试")).when(dao).voidTest();
try {
service.voidTest();
} catch (Exception e) {
Assert.assertEquals("测试", e.getMessage());
}

// 不能模拟抛Exception类
// when(dao.update("3", "4")).thenThrow(new Exception());

// 同一方法不能多次模拟抛异常
// when(dao.update("3", "4")).thenThrow(new NullPointerException());
// Assert.assertEquals(-1, service.update("3", "4"));
}
}

class Service {
private Dao dao;

public void setDao(Dao dao) {
this.dao = dao;
}

public void voidTest() {
dao.voidTest();
}

public int update(String a, String b) {
int i = 0;
try {
i = dao.update(a, b);
} catch (Exception e) {
i = -1;
}
return i;
}
}

class Dao {
public void voidTest() {
}

public int update(String a, String b) {
return 1;
}
}



附上maven依赖

org.mockito
mockito-all
1.8.5

你可能感兴趣的:(单元测试)