Android单元测试Mock

@Config(manifest = Config.NONE)
//模拟上下文
@RunWith(RobolectricTestRunner.class)
@PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "android.*"})
//需要Mock的类
@PrepareForTest({MDVRServerMessageProcessor.class})
public class MDVRCommunicationTest {
	//Mock和上下文同时用时,@RunWith只能用一个,这里是Mock的另一种配置方式
    @Rule
    public PowerMockRule rule = new PowerMockRule();

	//测试前
    @Before
    public void setUp() throws Exception {
        Context mockContext = RuntimeEnvironment.application;
        MDVRCommunicationManager.getInstance().init(mockContext);
    }

	//测试后
    @After
    public void tearDown() throws Exception {
        MDVRCommunicationManager.getInstance().release();
    }

    @Test
    public void testRealtimeDataCmd() throws Exception {
        MDVRServerMessageProcessor mockProcessor = PowerMockito.spy(new MDVRServerMessageProcessor());
        String hexStrOfCmd = "9700030000003100000000000C0000000001DC732F073BBC7D021909261105000001";
        byte[] bytesOfCmd = HexStringUtils.hexString2Bytes(hexStrOfCmd);
        MDVRMessage message = new MDVRMessage(bytesOfCmd);
        //实时数据指令
        mockProcessor.process(bytesOfCmd);
        //验证私有方法调用
        PowerMockito.verifyPrivate(mockProcessor, Mockito.times(1)).invoke("handleRealtimeData", Mockito.any());
    }

    @Test
    public void onAuth() throws Exception {
        //模拟鉴权事件
        mMockCommunicationInstance.init(mMockContext);
        String testAuthCode = "0000";
        AuthEvent event = new AuthEvent(testAuthCode, null);
        mMockCommunicationInstance.onAuth(event);

        //验证私有方法调用
        PowerMockito.verifyPrivate(mMockCommunicationInstance, Mockito.times(1)).invoke("auth", Mockito.any(), Mockito.any());
        //验证鉴权消息生成 (注意下面两句放在一起,进行static方法调用验证)
        PowerMockito.verifyStatic(Mockito.times(1));
        JT808Generator.generateAuthMsg(mMockContext, testAuthCode, 0);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值