前言
讀者有沒發覺我寫文章時,喜歡有個前言、序?真相是,一半用來裝逼湊字數,一半是因為不知道接下來要寫什么,先閑聊幾句壓壓驚_ 哈哈哈......該說的還是要說。
上一篇《Android單元測試 - Sqlite、SharedPreference、Assets、文件操作 怎么測?》 講了一些DAO(Data Access Object)單元測試的細節。本篇講解參數驗證。
驗證參數傳遞、函數返回值,是單元測試中十分重要的環節。筆者相信不少讀者都有驗證過參數,但是你的單元測試代碼真的是正確的嗎?筆者在早期實踐的時候,遇到一些問題,積累了一點心得,本期與大家分享一下。
1.一般形式
Bean
public class Bean {
int id;
String name;
public Bean(int id, String name) {
this.id = id;
this.name = name;
}
// getter and setter
......
}
DAO
public class DAO {
public Bean get(int id) {
return new Bean(id, "bean_" + id);
}
}
Presenter
public class Presenter {
DAO dao;
public Presenter(DAO dao) {
this.dao = dao;
}
public Bean getBean(int id) {
Bean bean = dao.get(id);
return bean;
}
}
單元測試PresenterTest
(下文稱為“例子1”)
public class PresenterTest {
DAO dao;
Presenter presenter;
@Before
public void setUp() throws Exception {
dao = mock(DAO.class);
presenter = new Presenter(dao);
}
@Test
public void testGetBean() throws Exception {
Bean bean = new Bean(1, "bean_1");
when(dao.get(1)).thenReturn(bean);
Bean result = presenter.getBean(1);
Assert.assertEquals(result.getId(), 1);
Assert.assertEquals(result.getName(), "bean_1");
}
}
這個單元測試是通過的。
2.問題:對象很多變量
上面的Bean
只有2個參數,但實際項目,對象往往有很多很多參數,例如,用戶信息User
:
public class User {
int id;
String name;
String country;
String province;
String city;
String address;
int zipCode;
long birthday;
double height;
double weigth;
...
}
單元測試:
@Test
public void testUser() throws Exception {
User user = new User(1, "bean_1");
user.setCountry("中國");
user.setProvince("廣東");
user.setCity("廣州");
user.setAddress("天河區臨江大道海心沙公園");
user.setZipCode(510000);
user.setBirthday(631123200);
user.setHeight(173);
user.setWeigth(55);
user.setXX(...);
.....
User result = presenter.getUser(1);
Assert.assertEquals(result.getId(), 1);
Assert.assertEquals(result.getName(), "bean_1");
Assert.assertEquals(result.getCountry(), "中國");
Assert.assertEquals(result.getProvince(), "廣東");
Assert.assertEquals(result.getCity(), "廣州");
Assert.assertEquals(result.getAddress(), "天河區臨江大道海心沙公園");
Assert.assertEquals(result.getZipCode(), 510000);
Assert.assertEquals(result.getBirthday(), 631123200);
Assert.assertEquals(result.getHeight(), 173);
Assert.assertEquals(result.getWeigth(), 55);
Assert.assertEquals(result.getXX(), ...);
......
}
一般形式的單元測試,有10個參數,就要set()
10次,get()
10次,如果參數更多,一個工程有幾十上百個這種測試......感受到那種蛋蛋的痛了嗎?
這里有兩個痛點:
1.生成對象必須 調用所有
setter()
賦值成員變量
2.驗證返回值,或者回調參數時,必須 調用所有getter()
獲取成員值
3.equals()對比對象,可行嗎?
直接調用equals()
這時同學A舉手了:“不就是比較對象嗎,用
equal()
還不行?”
為了演示方便,還是用回Bean
做例子:
@Test
public void testGetBean() throws Exception {
Bean bean = new Bean(1, "bean_1");
when(dao.get(1)).thenReturn(bean);
Bean result = presenter.getBean(1);
Assert.assertTrue(result.equals(bean));
}
運行一下:
誒,還真通過了!第一個問題解決了,鼓掌..... 稍等,我們把Presenter
代碼改改,看還能不能湊效:
public class Presenter {
public Bean getBean(int id) {
Bean bean = dao.get(id);
return new Bean(bean.getId(), bean.getName());
}
}
再運行單元測試:
果然出錯了!
我們分析一下問題,修改前的Presenter.getBean()
方法, dao.get()
得到的Bean
對象,直接作為返回值,所以PresenterTest
中Assert.assertTrue(result.equals(bean));
通過測試,因為bean
和result
是同一個對象;修改后,Presenter.getBean()
里,返回值是dao.get()
得到的Bean
的深拷貝,bean
和result
是不同對象,因此result.equals(bean)==false
,測試失敗。如果我們使用一般形式Assert.assertEquals(result.getXX(), ...);
,單元測試是通過的。
無論是直接返回對象,深拷貝,只要參數一致,都符合我們期望的結果。所以,僅僅調用equals()
解決不了問題。
重寫equals()方法
同學B:“既然只是比較成員值,重寫equals()!”
public class Bean {
@Override
public boolean equals(Object obj) {
if (obj instanceof Bean) {
Bean bean = (Bean) obj;
boolean isEquals = false;
if (isEquals) {
isEquals = id == bean.getId();
}
if (isEquals) {
isEquals = (name == null && bean.getName() == null) || (name != null && name.equals(bean.getName()));
}
return isEquals;
}
return false;
}
}
再次運行單元測試Assert.assertTrue(result.equals(bean));
:
稍等,這樣我們不是回到老路,每個java bean
都要重寫equals()
嗎?盡管整個工程下來,總體代碼會減少,但這真不是好辦法。
反射比較成員值
同學C:“我們可以用反射獲取兩個對象所有成員值,并逐一對比。”
哈哈哈,同學C比同學A、B都要聰明點,還會反射!
public class PresenterTest{
@Test
public void testGetBean() throws Exception {
...
ObjectHelper.assertEquals(bean, result);
}
}
public class ObjectHelper {
public static boolean assertEquals(Object expect, Object actual) throws IllegalAccessException {
if (expect == actual) {
return true;
}
if (expect == null && actual != null || expect != null && actual == null) {
return false;
}
if (expect != null) {
Class clazz = expect.getClass();
while (!(clazz.equals(Object.class))) {
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
Object value0 = field.get(expect);
Object value1 = field.get(actual);
Assert.assertEquals(value0, value1);
}
clazz = clazz.getSuperclass();
}
}
return true;
}
}
運行單元測試,通過!
用反射直接對比成員值,思路是正確的。這里解決了“對比兩個對象的成員值是否相同,不需要get()
n次”問題。不過,僅僅比較兩個對象,這個單元測試還是有問題的。我們先講第4節,這個問題留在第5節給大家說明。
4.省略不必要setter()
在testUser()
中,第一個痛點:“生成對象必須 調用所有setter()
賦值成員變量”。 上一節同學C用反射方案,把對象成員值拿出來,逐一比較。這個方案提醒了我們,賦值也可以同樣方案。
ObjectHelper
:
public class ObjectHelper {
protected static final List numberTypes = Arrays.asList(int.class, long.class, double.class, float.class, boolean.class);
public static <T> T random(Class<T> clazz) throws IllegalAccessException, InstantiationException {
try {
T obj = newInstance(clazz);
Class tClass = clazz;
while (!tClass.equals(Object.class)) {
Field[] fields = tClass.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
Class type = field.getType();
int modifiers = field.getModifiers();
// final 不賦值
if (Modifier.isFinal(modifiers)) {
continue;
}
// 隨機生成值
if (type.equals(Integer.class) || type.equals(int.class)) {
field.set(obj, new Random().nextInt(9999));
} else if (type.equals(Long.class) || type.equals(long.class)) {
field.set(obj, new Random().nextLong());
} else if (type.equals(Double.class) || type.equals(double.class)) {
field.set(obj, new Random().nextDouble());
} else if (type.equals(Float.class) || type.equals(float.class)) {
field.set(obj, new Random().nextFloat());
} else if (type.equals(Boolean.class) || type.equals(boolean.class)) {
field.set(obj, new Random().nextBoolean());
} else if (CharSequence.class.isAssignableFrom(type)) {
String name = field.getName();
field.set(obj, name + "_" + (int) (Math.random() * 1000));
}
}
tClass = tClass.getSuperclass();
}
return obj;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected static <T> T newInstance(Class<T> clazz) throws IllegalAccessException, InvocationTargetException, InstantiationException {
Constructor constructor = clazz.getConstructors()[0];// 構造函數可能是多參數
Class[] types = constructor.getParameterTypes();
List<Object> params = new ArrayList<>();
for (Class type : types) {
if (Number.class.isAssignableFrom(type) || numberTypes.contains(type)) {
params.add(0);
} else {
params.add(null);
}
}
T obj = (T) constructor.newInstance(params.toArray());//clazz.newInstance();
return obj;
}
}
寫個單元測試,生成并隨機賦值的Bean
,輸出Bean
所有成員值:
@Test
public void testNewBean() throws Exception {
Bean bean = ObjectHelpter.random(Bean.class);
// 輸出bean
System.out.println(bean.toString()); // toString()讀者自己重寫一下吧
}
運行測試:
Bean {id: 5505, name: "name_145"}
修改單元測試
單元測試PresenterTest
:
public class PresenterTest {
@Test
public void testUser() throws Exception {
User expect = ObjectHelper.random(User.class);
when(dao.getUser(1)).thenReturn(expect);
User actual = presenter.getUser(1);
ObjectHelper.assertEquals(expect, actual);
}
}
代碼少了許多,很爽有沒有?
運行一下,通過:
5.比較對象bug
上述筆者提到的解決方案,有一個問題,看以下代碼:
Presenter
:
public class Presenter {
DAO dao;
public Bean getBean(int id) {
Bean bean = dao.get(id);
// 臨時修改bean值
bean.setName("我來搗亂");
return new Bean(bean.getId(), bean.getName());
}
}
@Test
public void testGetBean() throws Exception {
Bean expect = random(Bean.class);
System.out.println("expect: " + expect);// 提前輸出expect
when(dao.get(1)).thenReturn(expect);
Bean actual = presenter.getBean(1);
System.out.println("actual: " + actual);// 輸出結果
ObjectHelper.assertEquals(expect, actual);
}
運行一下修改后的單元測試:
Pass
expect: Bean {id=3282, name='name_954'}
actual: Bean {id=3282, name='我來搗亂'}
居然通過了!(不符合預期結果)這是怎么回事?
筆者給大家分析下:我們希望返回的結果是Bean{id=3282, name='name_954'}
,但是在Presenter
里mock指定的返回對象Bean
被修改了,同時返回的Bean
深拷貝對象,變量name
也跟著變;運行單元測試時,在最后才比較兩個對象的成員值,兩個對象的name
都被修改了,導致equals()
認為是正確。
這里的問題:
在
Presenter
內部篡改了mock指定返回對象的成員值
最簡單的解決方法:
在調用
Presenter
方法前,把的mock返回對象的成員參數,提前拿出來,在單元測試最后比較。
修改單元測試:
@Test
public void testGetBean() throws Exception {
Bean expect = random(Bean.class);
int id = expect.getId();
String name = expect.getName();
when(dao.get(1)).thenReturn(expect);
Bean actual = presenter.getBean(1);
// ObjectHelper.assertEquals(expect, actual);
Assert.assertEquals(id, actual.getId());
Assert.assertEquals(name, actual.getName());
}
運行,測試不通過(符合預期結果):
org.junit.ComparisonFailure:
Expected :name_825
Actual :我來搗亂
符合我們期望值(測試不通過)!等等....這不就回到老路了嗎?當有很多成員變量,不就寫到手軟?前面講的都白費了?
接下來,進入本文高潮。
6.解決方案1:提前深拷貝expect對象
public class ObjectHelpter {
public static <T> T copy(T source) throws IllegalAccessException, InstantiationException, InvocationTargetException {
Class<T> clazz = (Class<T>) source.getClass();
T obj = newInstance(clazz);
Class tClass = clazz;
while (!tClass.equals(Object.class)) {
Field[] fields = tClass.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
Object value = field.get(source);
field.set(obj, value);
}
tClass = tClass.getSuperclass();
}
return obj;
}
}
單元測試:
@Test
public void testGetBean() throws Exception {
Bean bean = ObjectHelpter.random(Bean.class);
Bean expect = ObjectHelpter.copy(bean);
when(dao.get(1)).thenReturn(bean);
Bean actual = presenter.getBean(1);
ObjectHelpter.assertEquals(expect, actual);
}
運行一下,測試不通過,great(符合想要的結果):
我們把Presenter
改回去:
public class Presenter {
DAO dao;
public Bean getBean(int id) {
Bean bean = dao.get(id);
// bean.setName("我來搗亂");
return new Bean(bean.getId(), bean.getName());
}
}
再運行單元測試,通過:
7.解決方案2:對象->JSON,比較JSON
看到這節標題,大家都明白怎么回事了吧。例子中,我們會用到Gson。
Gson
public class PresenterTest{
@Test
public void testBean() throws Exception {
Bean bean = random(Bean.class);
String expectJson = new Gson().toJson(bean);
when(dao.get(1)).thenReturn(bean);
Bean actual = presenter.getBean(1);
Assert.assertEquals(expectJson, new Gson().toJson(actual, Bean.class));
}
}
運行:
測試失敗的場景:
@Test
public void testBean() throws Exception {
Bean bean = random(Bean.class);
String expectJson = new Gson().toJson(bean);
when(dao.get(1)).thenReturn(bean);
Bean actual = presenter.getBean(1);
actual.setName("我來搗亂");// 故意讓單元測試出錯
Assert.assertEquals(expectJson, new Gson().toJson(actual, Bean.class));
}
運行,測試不通過(符合預計結果):
咋看沒什么問題。但如果成員變量很多,這時單元測試報錯呢?
@Test
public void testUser() throws Exception {
User user = random(User.class);
String expectJson = new Gson().toJson(user);
when(dao.getUser(1)).thenReturn(user);
User actual = presenter.getUser(1);
actual.setWeigth(10);// 錯誤值
Assert.assertEquals(expectJson, new Gson().toJson(actual, User.class));
}
你看出哪里錯了嗎?你要把窗口滾動到右邊,才看到哪個字段不一樣;而且當對象比較復雜,就更難看了。怎么才能更人性化提示?
JsonUnit
筆者給大家介紹一個很強大的json比較庫——Json Unit.
gradle引入:
dependencies {
compile group: 'net.javacrumbs.json-unit', name: 'json-unit', version: '1.16.0'
}
maven引入:
<dependency>
<groupId>net.javacrumbs.json-unit</groupId>
<artifactId>json-unit</artifactId>
<version>1.16.0</version>
</dependency>
import static net.javacrumbs.jsonunit.JsonAssert.assertJsonEquals;
@Test
public void testUser() throws Exception {
User user = random(User.class);
String expectJson = new Gson().toJson(user);
when(dao.getUser(1)).thenReturn(user);
User actual = presenter.getUser(1);
actual.setWeigth(10);// 錯誤值
assertJsonEquals(expectJson, actual);
}
運行,測試不通過(符合預期結果):
讀者可以看到Different value found in node "weigth". Expected 0.005413020868182183, got 10.0.
,意思節點weigth
期望值0.005413020868182183
,但是實際值10.0
。
無論json多復雜,JsonUnit都可以顯示哪個字段不同,讓使用者最直觀地定位問題。JsonUnit還有很多好處,前后參數可以json+對象,不要求都是json或都是對象;對比List
時,可以忽略List
順序.....
DAO
public class DAO {
public List<Bean> getBeans() {
return ...; // sql、sharePreference操作等
}
}
Presenter
public class Presenter {
DAO dao;
public List<Bean> getBeans() {
List<Bean> result = dao.getBeans();
Collections.reverse(result); // 反轉列表
return result;
}
}
PresenterTest
@Test
public void testList() throws Exception {
Bean bean0 = random(Bean.class);
Bean bean1 = random(Bean.class);
List<Bean> list = Arrays.asList(bean0, bean1);
String expectJson = new Gson().toJson(list);
when(dao.getBeans()).thenReturn(list);
List<Bean> actual = presenter.getBeans();
Assert.assertEquals(expectJson, new Gson().toJson(actual));
}
運行,單元測試不通過(預期結果):
對于junit來說,列表順序不同,生成的json string不同,junit報錯。對于“代碼非常在意列表順序”場景,這邏輯是正確的。但是很多時候,我們并不那么在意列表順序。這種場景下,junit + gson就蛋疼了,但是JsonUnit可以簡單地解決:
@Test
public void testList() throws Exception {
Bean bean0 = random(Bean.class);
Bean bean1 = random(Bean.class);
List<Bean> list = Arrays.asList(bean0, bean1);
String expectJson = new Gson().toJson(list);
when(dao.getBeans()).thenReturn(list);
List<Bean> actual = presenter.getBeans();
// Assert.assertEquals(expectJson, new Gson().toJson(actual));
// expect是json,actual是對象,jsonUnit都沒問題
assertJsonEquals(expectJson, actual, JsonAssert.when(Option.IGNORING_ARRAY_ORDER));
}
運行單元測試,通過:
JsonUnit還有很多用法,讀者可以上github看看介紹,有大量測試用例,供使用者參考。
解析json的場景
對于測試json解析的場景,JsonUnit的簡介就更明顯了。
public class Presenter {
public Bean parse(String json) {
return new Gson().fromJson(json, Bean.class);
}
}
@Test
public void testParse() throws Exception {
String json = "{\"id\":1,\"name\":\"bean\"}";
Bean actual = presenter.parse(json);
assertJsonEquals(json, actual);
}
運行,測試通過:
一個json,一個bean作為參數,都沒問題;如果是Gson的話,還要把Bean
轉成json去比較。
小結
感覺這次談了沒多少東西,但文章很冗長,繁雜的代碼挺多。嘮嘮叨叨地講了一大堆,不知道讀者有沒看明白,本文寫作順序,就是筆者當時探索校驗參數的經歷。這次沒什么高大上的概念,就是基礎的、容易忽略的東西,在單元測試中也十分好用,希望讀者好好體會。
單元測試的細節,已經講得七七八八了。下一篇再指導一下項目使用單元測試,單元測試的系列就差不多完結。當然以后有更多心得,還會寫的。
關于作者
我是鍵盤男。
在廣州生活,在互聯網公司上班,猥瑣文藝碼農。喜歡科學、歷史,玩玩投資,偶爾獨自旅行。