Kyl*_*ner 4 android unit-testing mockito
我有一个自定义视图,我正在尝试针对不同的屏幕尺寸进行测试,但我无法找到有关如何在单元测试中正确模拟显示宽度的文档或示例。
这是我如何尝试使用它的示例:
private CustomTextView customTV;
@Override
protected void setUp() throws Exception {
super.setUp();
DisplayMetrics displayMetrics = mock(DisplayMetrics.class);
displayMetrics.widthPixels = 600;
Resources mockResources = mock(Resources.class);
when(mockResources.getDisplayMetrics()).thenReturn(displayMetrics);
Context mockContext = mock(Context.class);
when(mockContext.getResources()).thenReturn(mockResources);
customTV = new CustomTextView(mockContext);
}
@SmallTest
public void testViewSize() {
Assert.assertEquals("Text size did not scale", 42, customTV.getTextSize());
}
Run Code Online (Sandbox Code Playgroud)
此外,我仅在某些设备上遇到错误(上述实现适用于某些屏幕尺寸,但不是全部):
Error in testViewSize:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.content.res.Configuration.isLayoutSizeAtLeast(int)' on a null object reference
at android.view.ViewConfiguration.<init>(ViewConfiguration.java:284)
at android.view.ViewConfiguration.get(ViewConfiguration.java:364)
at android.view.View.<init>(View.java:3781)
at android.view.View.<init>(View.java:3876)
at android.widget.TextView.<init>(TextView.java:655)
at android.widget.TextView.<init>(TextView.java:650)
at android.widget.TextView.<init>(TextView.java:646)
at com.foo.bar.view.CustomTextView.<init>(CustomTextView.java:55)
at com.foo.bar.view.CustomTextView.<init>(CustomTextView.java:45)
at com.foo.bar.view.CustomTextViewTests.setUp(CustomTextViewTests.java:52)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:191)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:176)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:557)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1874)
Run Code Online (Sandbox Code Playgroud)
我真正想要做的就是将 的返回值设置displayMetrics.widthPixels为特定数字,但是因为它不是方法调用,如 getter 或 setter,所以我无法像在其他模拟中使用whenandthenReturn方法那样覆盖它对象。
是否有更简单的方法来模拟 Context/Resources/DisplayMetrics?
为了回答你的问题,你就像在做一样嘲笑它。
DisplayMetrics metrics = mock(DisplayMetrics.class);
metrics.widthPixels = 300;
Resources resources = mock(Resources.class);
when(resources.getDisplayMetrics()).thenReturn(metrics);
Assert.assertEquals(300, resources.getDisplayMetrics().widthPixels);
// ^^ see proof
Run Code Online (Sandbox Code Playgroud)
您发布的错误消息只是表明您需要模拟更多对象。你做得还不够。
java.lang.NullPointerException: 尝试调用虚拟方法 'boolean android.content.res.Configuration
所以也要模拟 Configuration 对象。
编辑:
如果您使用的是 Robolectric,则显示使用真实配置的代码:
Context context = mock(Context.class);
Resources resources = mock(Resources.class);
when(resources.getConfiguration()).thenReturn(RuntimeEnvironment.application.getResources().getConfiguration());
when(context.getResources()).thenReturn(resources);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1946 次 |
| 最近记录: |