0

我最近开始在 Android 上进行测试,并且一直在玩 Robolectric 和 Mockito。我可以使用 Robolectric 来模拟活动的生命周期。

但是,我的代码依赖于静态 util 函数来检索之前在启动期间创建的对象。

有没有办法模拟一个 util 类来返回一个模拟对象(最好是与真实对象相同的类型)?一直使用 Robolectric 来控制活动生命周期。

public class SomeActivity extends Activity
{
  @Override
  public void onCreate( Bundle b )
  {
     super.onCreate(b);
     Something thing = SomeUtil.getSomething();  //I want to put my mocked obj in 'thing'
  }
}
class SomeUtil 
{
  Something something;
  // I want to mock what this func returns by returning my own mock obj
  public static Something getSomething()
  {
     return something; 
  }
}

我不仅限于使用 Robolectric 或 Mockito。

4

1 回答 1

1

I haven't personally used it, but I've heard that PowerMock allows you to mock static methods.

In my experience though, I've found it nice to just avoid static methods altogether whenever possible and rely on dependency injection/mockito for mocking dependencies.

于 2013-10-16T21:40:53.177 回答