相关疑难解决方法(0)

PowerMockito:模拟上的NotAMockException

有点复杂的设置.Robolectric,PowerMockito基于规则的配置.

@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21)
@PowerMockIgnore({"org.mockito.*", "org.robolectric.*", "android.*"})
// Using "PrepareOnlyThis" prevents powermock from trying to instrument the whole hierarchy,
// part of which we've ignored (android.os.* in this case)
@PrepareOnlyThisForTest({ServiceCallbackBase.class}) // this class extends Handler, 
// so we need PrepareOnlyThis.  It also has some final methods we need to verify()
public class ServiceBaseTests {

  private class Foo {
    // nothing
  }

  @Rule
  public PowerMockRule rule = new PowerMockRule();

  private ServiceCallbackBase<Object, Foo> setupCallback( boolean hasValidContext, boolean allContextsCanceled …
Run Code Online (Sandbox Code Playgroud)

android powermock robolectric powermockito

12
推荐指数
1
解决办法
3493
查看次数

在Android下测试Realm

我有一个Android应用程序,我使用Realm来保存数据.我现在想利用Realm为这个应用程序编写一个单元测试.

但是,我不希望单元测试干扰我现有的Realm数据.所以我想为我的测试实例生成不同的Realm文件.我不在乎他们是否有不同的名称,或者存储在不同的目录中.

我试过用a RenamingDelegatingContext,但没有成功.根据https://groups.google.com/forum/#!msg/realm-java/WyHJHLOqK2c/WJFYvglIGk0J getInstance()仅使用Contextto调用getFilesDir(),这似乎没有覆盖该getFilesDir()方法,所以我最终使用我的实时数据测试.

接下来我尝试使用IsolatedContext,但IsolatedContext.getFilesDir()返回null,所以这也没有成功.

最后,我尝试编写一个类扩展RenamingDelegatingContext,覆盖getFilesDir(),返回一个不同的目录供Realm使用.我使用AndroidStudio的DeviceMonitor创建了目录,但是当我尝试使用这个上下文时,Realm失败了io.realm.exceptions.RealmIOException: Failed to open . Permission denied. open() failed: Permission denied.

有没有人知道是否有可能在不影响实时数据的情况下测试Realm?

java android unit-testing realm

7
推荐指数
2
解决办法
4384
查看次数

Android InstrumentationTestCase getFilesDir()返回null

我正在使用InstrumentationTestCase单元测试我的应用程序的一个组件.

该组件将数据持久保存到内部存储,并用于Context::fileList();检索持久文件.

我遇到以下问题:在应用程序中使用此方法(在设备上)工作完全正常.但是,当我尝试(Android-)单元测试(也在设备上)使用InstrumentationTestCase我得到一个NullPointerException内部的fileList()方法.我深入研究android源代码并发现getFilesDir() (参见此处的源代码)返回null并导致此错误.

要重现的代码如下:

public class MyTestCase extends InstrumentationTestCase
{   
    public void testExample() throws Exception
    {
        assertNotNull(getInstrumentation().getContext().getFilesDir()); // Fails
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是:这种行为是否有意?我该怎么做才能绕过这个问题?我使用InstrumentationTestCase正确还是应该使用不同的东西?

我发现了这个问题,但我不确定这是否涵盖了我遇到的同样问题.

android unit-testing

6
推荐指数
1
解决办法
2806
查看次数