Android单元测试 mock Context,mock静态类的静态方法,测试方法的顺序

版权声明:本文为博主原创文章,转载请注明出处 https://blog.csdn.net/u011109881/article/details/86157971

mock Context

我们写单元测试时,经常会用到context对象,但是直接使用context经常报空指针异常
正确的mock方式如下
1.添加变量

@Mock
private Context mockApplicationContext;

2.在setUp方法中初始化

@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
}

3.在使用到context的地方灵活使用mockito的when方法
比如我们用到context经常是因为String的关系,可以这样用

        when(mockApplicationContext.getString(R.string.filterOthers))
                .thenReturn("Other");

mock静态类的静态方法

在我们测试时经常遇到静态类的静态方法无法通过测试,比如TextUtils
其mock顺序如下
1.测试类前声明

@RunWith(PowerMockRunner.class)
@PrepareForTest({TextUtils.class, Xxx.class})
public class Xxx{
}

2.初始化

    @Before
    public void setUp() throws Exception {
        PowerMockito.mockStatic(TextUtils.class);
    }

3.在具体的测试方法灵活使用mockito的when方法
比如

        when(TextUtils.isEmpty(price.getType()))
                .thenReturn(price.getType().length() == 0);

测试方法的顺序

我们写测试方法时经常会遇到方法A调用B 方法B调用方法C的情况比如

		if(flag1 == true){
			methodA();
		}else{
			methodB(key);
		}
		
		methodA(){
			if(flag2 == true){
				methodC();
			}else{
				methodD();
			}
		}
		
		methodB(key){
			switch (key) {
			case a:
				methodE();
				break;
			case b:
				methodF();
				break;
			case c:
				methodG();
				break;
			default:
				break;
			}
		}

那么我们写测试方法的顺序从末端的方法写会容易一些,比如上面这个例子我们写的顺序是EFG CD AB(组内顺序不区分)
当然如果写测试方法写的多了应该知道为方法A写测试方法时只要把两个分支都测了就OK了其实与方法内部调用的方法C和方法D没有关系。但是对于刚接触单元测试的我来说,这样写感觉上简单一些哈哈。

猜你喜欢

转载自blog.csdn.net/u011109881/article/details/86157971
今日推荐