当前位置: 首页 > 工具软件 > Answer > 使用案例 >

Mockito之使用Answer

萧懿轩
2023-12-01

目录

Answer的基本用法:

 被测试类:DataSet.java

使用场景一:模拟Cursor

使用场景二:获取方法传入的参数,及验证参数或对参数断言

使用场景三:获取匿名内部类,对匿名内部类进行单元测试


Answer的基本用法:

Subject.java

public class Subject{
        public int getInt(){
            return 1;
        }
    }

测试用例

        Answer answer = new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                String method = invocation.getMethod().getName();
                if(method == "getInt"){
                    return 0;
                }
                return null;
            }
        };
        Subject subject = mock(Subject.class);
        when(subject.getInt()).thenAnswer(answer);
        System.out.println(subject.getInt());

输出结果:0

 

 被测试类:DataSet.java

public class DataSet {
    private List<String> mData = new ArrayList(4);
    private static String TAG = "DataSet";
    ExecutorService mService;
    public List<String> getData(ContentResolver resolver){
        Uri uri = Uri.parse("uriString");
        List<String> data = new ArrayList(8);
        Cursor cursor = resolver.query(uri, null, null, null, null);
        if(cursor != null && cursor.getCount() > 0){
            while(cursor.moveToNext()){
                data.add(cursor.getString(0));
            }
            mData = data;
            return data;
        }
        return null;
    }

    public void add(String s){
        if(s.startsWith("a")){
            mData.add(s);
            print(TAG, "info", s);
        }
    }

    public void print(String tag, String level, String info){
        System.out.println(tag + "    " + level + " : " + info);
    }

    public void saveData(){
        StringBuilder sb = new StringBuilder(64);
        for(String s : mData){
            sb.append(s);
        }
        final String data = sb.toString();
        if(data.length() > 0){
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    File file = new File("data.txt");
                    if(file.exists()){
                        if(!file.delete()){
                            Log.e(TAG, "delete file failed!!!");
                            return;
                        }
                    }
                    FileWriter writer =  null;
                    try {
                        writer = new FileWriter(file);
                        BufferedWriter bw = new BufferedWriter(writer);
                        bw.write(data);
                        print(TAG, "info", "save data successed!!!");
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }finally {
                        if(writer != null){
                            try {
                                writer.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                }
            };
            execute(runnable);
        }


    }

    public void execute(Runnable task){
        if(mService == null){
            mService = Executors.newSingleThreadExecutor();
        }
        mService.execute(task);
    }
}

使用场景一:模拟Cursor

测试用例

        final String[] arr = new String[]{"a", "b", "c", "d"};
        final int count = 8;
        Answer answer = new Answer() {
            int size = count;
            int pos = -1;
            String[] data = arr;
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                String method = invocation.getMethod().getName();
                switch(method){
                    case "moveToNext":
                        return ++pos < size;
                    case "getCount":
                        return size;
                    case "getString":
                        int index = invocation.getArgument(0);
                        if(index == 0){
                            return String.valueOf(data[pos%data.length]);
                        }
                }
                return null;
            }
        };
        Cursor cursor = mock(Cursor.class, answer);
        ContentResolver contentResolver = mock(ContentResolver.class);
        when(contentResolver.query(any(Uri.class), (String[])isNull(), (String)isNull(),
                (String[])isNull(), (String) isNull())).thenReturn(cursor);

        DataSet dataSet = new DataSet();
        //invoke getData()
        List result = dataSet.getData(contentResolver);
        //assert
        assertEquals(count, result.size());

 

使用场景二:获取方法传入的参数,及验证参数或对参数断言

 测试用例

    String mStr;
    @Test
    public void should_str_equalsTo_mStr_when_add_with_str_startWith_a(){
        Answer answer = new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                int indexOfInfo = 2;
                mStr = invocation.getArgument(indexOfInfo);
                return null;
            }
        };
        DataSet dataSet = new DataSet();
        dataSet = spy(dataSet);
        doAnswer(answer).when(dataSet).print(anyString(), anyString(), anyString());
        String str = "ad";
        dataSet.add(str);
        //验证是否走入if分支
        assertEquals(str, mStr);
    }

 

使用场景三:获取匿名内部类,对匿名内部类进行单元测试

测试用例

@Test
    public void should_call_print_with_String_contains_successed_when_saveData_with_mData_not_empty(){
        Answer answer = new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                //因为无法与runnable同步,无法验证run方法什么时候跑完,
                // 所以就使用answer获取Runnable,并调用run方法
                Runnable runnable = invocation.getArgument(0);
                runnable.run();
                return null;
            }
        };
        DataSet dataSet = new DataSet();
        dataSet = spy(dataSet);
        //string startWith "a",init DataSet#mData
        String data = "abb";
        dataSet.add(data);
        doAnswer(answer).when(dataSet).execute(any(Runnable.class));
        //invoke saveData()
        dataSet.saveData();
        //验证成功写完数据
        verify(dataSet, times(1)).print(anyString(), anyString(), contains("successed"));
    }

 

 类似资料: