无法存根android.os.Handler类的post方法 [英] Not able to stub post method of android.os.Handler class

查看:106
本文介绍了无法存根android.os.Handler类的post方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Junit4Mockito编写测试用例.在正在测试的一个类中,有一个函数init(),它从构造函数中调用.

I am using Junit4 and Mockito for writing my test cases. In one of the classes which is under test, there is a function init(), which gets called from the constructor.

void init(){
//Some code 
  Handler handler = new Handler(Looper.getMainLooper());
    handler.post(new Runnable() {
      @Override
      public void run() {
        //Some code
      }
    });
}

尝试创建该类的constructor时,引发以下异常.

The following exception is thrown when trying to create constructor of that class.

java.lang.RuntimeException: Method post in android.os.Handler not mocked.

然后我尝试使用以下代码模拟Handler类的post方法

Then I tried to mock post method of the Handler class using the following code

Handler handler = spy(new Handler());
when(handler.post(Matchers.any(Runnable.class))).thenReturn(true);

但是我仍然继续得到相同的exception.我该如何处理Handler类的post方法?

But still I keep on getting the same exception. What should I do to stub the post method of the Handler class ?

推荐答案

得到了相同的错误( java.lang.RuntimeException:android.os.Handler中的方法postDelayed未模拟),并最终通过将处理程序传递给类构造函数来解决该问题,甚至不需要再对其进行存根了.

Got the same error(java.lang.RuntimeException: Method postDelayed in android.os.Handler not mocked), and ended up to resolve the issue by passing the handler into the class constructor and don't even need to stub it anymore.

样本测试班

@RunWith(MockitoJUnitRunner::class)
class MainViewModelImplTest {

    @Mock
    lateinit var handler: Handler

    lateinit var mainViewModel: MainViewModel

    @Before
    fun setUp() {
        mainViewModel = MainViewModelImpl(handler = handler)
    }

    @After
    fun tearDown() {
    }

    @Test
    fun testDoStuff() {
        mainViewModel.doStuff()

        //verifty...
        //assert...
    }

}

要测试的示例类别

class MainViewModelImpl
@Inject constructor(
    val handler: Handler
): ViewModel() {
    private val task = object : Runnable {
        override fun run() {
            // do things
            handler.postDelayed(this, 60 * 1000)
        }
    }

    fun doStuff() {
        task.run()
    }
}

这篇关于无法存根android.os.Handler类的post方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆