Android單元測試 - 驗(yàn)證函數(shù)參數(shù)、返回值的正確姿勢
原文鏈接:http://www.jianshu.com/p/77ee7c0270bc
前言
讀者有沒發(fā)覺我寫文章時(shí),喜歡有個(gè)前言、序?真相是,一半用來裝逼湊字?jǐn)?shù),一半是因?yàn)椴恢澜酉聛硪獙懯裁?,先閑聊幾句壓壓驚^_^ 哈哈哈......該說的還是要說。
上一篇《Android單元測試 - Sqlite、SharedPreference、Assets、文件操作 怎么測?》 講了一些DAO(Data Access Object)單元測試的細(xì)節(jié)。本篇講解參數(shù)驗(yàn)證。
驗(yàn)證參數(shù)傳遞、函數(shù)返回值,是單元測試中十分重要的環(huán)節(jié)。筆者相信不少讀者都有驗(yàn)證過參數(shù),但是你的單元測試代碼真的是正確的嗎?筆者在早期實(shí)踐的時(shí)候,遇到一些問題,積累了一點(diǎn)心得,本期與大家分享一下。
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");
 - }
 - }
 
這個(gè)單元測試是通過的。
2.問題:對象很多變量
上面的Bean只有2個(gè)參數(shù),但實(shí)際項(xiàng)目,對象往往有很多很多參數(shù),例如,用戶信息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("天河區(qū)臨江大道海心沙公園");
 - 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(), "天河區(qū)臨江大道海心沙公園");
 - 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個(gè)參數(shù),就要set()10次,get()10次,如果參數(shù)更多,一個(gè)工程有幾十上百個(gè)這種測試......感受到那種蛋蛋的痛了嗎?
這里有兩個(gè)痛點(diǎn):
- 生成對象必須 調(diào)用所有setter() 賦值成員變量
 - 驗(yàn)證返回值,或者回調(diào)參數(shù)時(shí),必須 調(diào)用所有g(shù)etter() 獲取成員值
 
3.equals()對比對象,可行嗎?
直接調(diào)用equals()
這時(shí)同學(xué)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));
 - }
 
運(yùn)行一下:
誒,還真通過了!第一個(gè)問題解決了,鼓掌..... 稍等,我們把Presenter代碼改改,看還能不能湊效:
- public class Presenter {
 - public Bean getBean(int id) {
 - Bean bean = dao.get(id);
 - return new Bean(bean.getId(), bean.getName());
 - }
 - }
 
再運(yùn)行單元測試:
果然出錯(cuò)了!
我們分析一下問題,修改前的Presenter.getBean()方法, dao.get()得到的Bean對象,直接作為返回值,所以PresenterTest中Assert.assertTrue(result.equals(bean));通過測試,因?yàn)閎ean和result是同一個(gè)對象;修改后,Presenter.getBean()里,返回值是dao.get()得到的Bean的深拷貝,bean和result是不同對象,因此result.equals(bean)==false,測試失敗。如果我們使用一般形式Assert.assertEquals(result.getXX(), ...);,單元測試是通過的。
無論是直接返回對象,深拷貝,只要參數(shù)一致,都符合我們期望的結(jié)果。所以,僅僅調(diào)用equals()解決不了問題。
重寫equals()方法
同學(xué)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;
 - }
 - }
 
再次運(yùn)行單元測試Assert.assertTrue(result.equals(bean));:
稍等,這樣我們不是回到老路,每個(gè)java bean都要重寫equals()嗎?盡管整個(gè)工程下來,總體代碼會減少,但這真不是好辦法。
反射比較成員值
同學(xué)C:“我們可以用反射獲取兩個(gè)對象所有成員值,并逐一對比。”
哈哈哈,同學(xué)C比同學(xué)A、B都要聰明點(diǎn),還會反射!
- 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;
 - }
 - }
 
運(yùn)行單元測試,通過!
用反射直接對比成員值,思路是正確的。這里解決了“對比兩個(gè)對象的成員值是否相同,不需要get()n次”問題。不過,僅僅比較兩個(gè)對象,這個(gè)單元測試還是有問題的。我們先講第4節(jié),這個(gè)問題留在第5節(jié)給大家說明。
4.省略不必要setter()
在testUser()中,第一個(gè)痛點(diǎn):“生成對象必須 調(diào)用所有setter() 賦值成員變量”。 上一節(jié)同學(xué)C用反射方案,把對象成員值拿出來,逐一比較。這個(gè)方案提醒了我們,賦值也可以同樣方案。
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;
 - }
 - // 隨機(jī)生成值
 - 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];// 構(gòu)造函數(shù)可能是多參數(shù)
 - 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;
 - }
 - }
 
寫個(gè)單元測試,生成并隨機(jī)賦值的Bean,輸出Bean所有成員值:
- @Test
 - public void testNewBean() throws Exception {
 - Bean bean = ObjectHelpter.random(Bean.class);
 - // 輸出bean
 - System.out.println(bean.toString()); // toString()讀者自己重寫一下吧
 - }
 
運(yùn)行測試:
- 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);
 - }
 - }
 
代碼少了許多,很爽有沒有?
運(yùn)行一下,通過:
5.比較對象bug
上述筆者提到的解決方案,有一個(gè)問題,看以下代碼:
Presenter:
- public class Presenter {
 - DAO dao;
 - public Bean getBean(int id) {
 - Bean bean = dao.get(id);
 - // 臨時(shí)修改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);// 輸出結(jié)果
 - ObjectHelper.assertEquals(expect, actual);
 - }
 
運(yùn)行一下修改后的單元測試:
- Pass
 - expect: Bean {id=3282, name='name_954'}
 - actual: Bean {id=3282, name='我來搗亂'}
 
居然通過了!(不符合預(yù)期結(jié)果)這是怎么回事?
筆者給大家分析下:我們希望返回的結(jié)果是Bean{id=3282, name='name_954'},但是在Presenter里mock指定的返回對象Bean被修改了,同時(shí)返回的Bean深拷貝對象,變量name也跟著變;運(yùn)行單元測試時(shí),在最后才比較兩個(gè)對象的成員值,兩個(gè)對象的name都被修改了,導(dǎo)致equals()認(rèn)為是正確。
這里的問題:
在Presenter內(nèi)部篡改了mock指定返回對象的成員值
最簡單的解決方法:
在調(diào)用Presenter方法前,把的mock返回對象的成員參數(shù),提前拿出來,在單元測試最后比較。
修改單元測試:
- @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());
 - }
 
運(yùn)行,測試不通過(符合預(yù)期結(jié)果):
- org.junit.ComparisonFailure:
 - Expected :name_825
 - Actual :我來搗亂
 
符合我們期望值(測試不通過)!等等....這不就回到老路了嗎?當(dāng)有很多成員變量,不就寫到手軟?前面講的都白費(fèi)了?
接下來,進(jìn)入本文高潮。
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);
 - }
 
運(yùn)行一下,測試不通過,great(符合想要的結(jié)果):
我們把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());
 - }
 - }
 
再運(yùn)行單元測試,通過:
7.解決方案2:對象->JSON,比較JSON
看到這節(jié)標(biāo)題,大家都明白怎么回事了吧。例子中,我們會用到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));
 - }
 - }
 
運(yùn)行:
測試失敗的場景:
- @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("我來搗亂");// 故意讓單元測試出錯(cuò)
 - Assert.assertEquals(expectJson, new Gson().toJson(actual, Bean.class));
 - }
 
運(yùn)行,測試不通過(符合預(yù)計(jì)結(jié)果):
咋看沒什么問題。但如果成員變量很多,這時(shí)單元測試報(bào)錯(cuò)呢?
- @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);// 錯(cuò)誤值
 - Assert.assertEquals(expectJson, new Gson().toJson(actual, User.class));
 - }
 
你看出哪里錯(cuò)了嗎?你要把窗口滾動到右邊,才看到哪個(gè)字段不一樣;而且當(dāng)對象比較復(fù)雜,就更難看了。怎么才能更人性化提示?
JsonUnit
筆者給大家介紹一個(gè)很強(qiáng)大的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);// 錯(cuò)誤值
 - assertJsonEquals(expectJson, actual);
 - }
 
運(yùn)行,測試不通過(符合預(yù)期結(jié)果):
讀者可以看到Different value found in node "weigth". Expected 0.005413020868182183, got 10.0.,意思節(jié)點(diǎn)weigth期望值0.005413020868182183,但是實(shí)際值10.0。
無論json多復(fù)雜,JsonUnit都可以顯示哪個(gè)字段不同,讓使用者最直觀地定位問題。JsonUnit還有很多好處,前后參數(shù)可以json+對象,不要求都是json或都是對象;對比List時(shí),可以忽略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); // 反轉(zhuǎn)列表
 - 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));
 - }
 
運(yùn)行,單元測試不通過(預(yù)期結(jié)果):
對于junit來說,列表順序不同,生成的json string不同,junit報(bào)錯(cuò)。對于“代碼非常在意列表順序”場景,這邏輯是正確的。但是很多時(shí)候,我們并不那么在意列表順序。這種場景下,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));
 - }
 
運(yùn)行單元測試,通過:
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);
 - }
 
運(yùn)行,測試通過:
一個(gè)json,一個(gè)bean作為參數(shù),都沒問題;如果是Gson的話,還要把Bean轉(zhuǎn)成json去比較。
小結(jié)
感覺這次談了沒多少東西,但文章很冗長,繁雜的代碼挺多。嘮嘮叨叨地講了一大堆,不知道讀者有沒看明白,本文寫作順序,就是筆者當(dāng)時(shí)探索校驗(yàn)參數(shù)的經(jīng)歷。這次沒什么高大上的概念,就是基礎(chǔ)的、容易忽略的東西,在單元測試中也十分好用,希望讀者好好體會。
單元測試的細(xì)節(jié),已經(jīng)講得七七八八了。下一篇再指導(dǎo)一下項(xiàng)目使用單元測試,單元測試的系列就差不多完結(jié)。當(dāng)然以后有更多心得,還會寫的。
關(guān)于作者
我是鍵盤男。在廣州生活,在互聯(lián)網(wǎng)公司上班,猥瑣文藝碼農(nóng)。喜歡科學(xué)、歷史,玩玩投資,偶爾獨(dú)自旅行。
































 
 
 







 
 
 
 