【问题标题】:How to run JUint Test with AndroidJUnitRunner如何使用 AndroidJUnitRunner 运行 JUnit 测试
【发布时间】:2017-05-22 13:27:22
【问题描述】:

我想为一些只需要 Android 上下文的代码编写一个 JUnit 测试,但我不想模拟我想要一个真实的上下文传递给我的对象。

我想初始化一个 Realm 实例。

【问题讨论】:

    标签: android unit-testing testing


    【解决方案1】:

    以下例子是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));
        }
    }
    

    Building Local Unit Tests

    【讨论】:

    • 我正在尝试初始化一个 Realm 实例,所以我不能使用模拟的上下文
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-09
    • 2019-12-25
    • 1970-01-01
    • 1970-01-01
    • 2011-05-31
    • 2015-03-26
    • 2011-05-29
    相关资源
    最近更新 更多