【发布时间】:2017-05-22 13:27:22
【问题描述】:
我想为一些只需要 Android 上下文的代码编写一个 JUnit 测试,但我不想模拟我想要一个真实的上下文传递给我的对象。
我想初始化一个 Realm 实例。
【问题讨论】:
标签: android unit-testing testing
我想为一些只需要 Android 上下文的代码编写一个 JUnit 测试,但我不想模拟我想要一个真实的上下文传递给我的对象。
我想初始化一个 Realm 实例。
【问题讨论】:
标签: android unit-testing testing
以下例子是google教程
它展示了如何创建使用模拟 Context 对象的单元测试。
要使用此框架将模拟对象添加到本地单元测试,请遵循以下编程模型:
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.*;
import static org.mockito.Mockito.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import android.content.SharedPreferences;
@RunWith(MockitoJUnitRunner.class)
public class UnitTestSample {
private static final String FAKE_STRING = "HELLO WORLD";
@Mock
Context mMockContext;
@Test
public void readStringFromContext_LocalizedString() {
// Given a mocked Context injected into the object under test...
when(mMockContext.getString(R.string.hello_word))
.thenReturn(FAKE_STRING);
ClassUnderTest myObjectUnderTest = new ClassUnderTest(mMockContext);
// ...when the string is returned from the object under test...
String result = myObjectUnderTest.getHelloWorldString();
// ...then the result should be the expected one.
assertThat(result, is(FAKE_STRING));
}
}
【讨论】: