Android PointF构造函数无法在JUnit测试中使用

dom96

我在尝试编写JUnit测试时偶然发现了这一点。诚然,这是我在JUnit中进行的首次单元测试,但是我的确感到非常困惑。

package com.example.dom.pointfbugrepro;

import android.graphics.PointF;
import org.junit.Test;
import static org.junit.Assert.*;

public class ExampleUnitTest {
    @Test
    public void pointf_isCorrect() throws Exception {
        PointF foo = new PointF(5, 0);
        assertEquals(5, foo.x, 0.0001f);
    }
}

在全新的Android项目中运行此测试会导致声明失败:

java.lang.AssertionError: 
Expected :5.0
Actual   :0.0

我在调查此问题时发现的一件事是x直接分配给PointF实例的字段确实有效。

那么这是什么问题呢?构造函数为什么不能正确设置字段?我应该如何测试使用PointF Android类的类?

JatraTim

参见http://tools.android.com/tech-docs/unit-testing-support#TOC-Method-...-not-mocked.-

当您运行单元测试时,您正在使用虚拟版本的android jar。通常,您会看到“方法...未模拟。”例外,但是由于您直接访问公共字段,因此这些只是默认值。

根据您的要求,您可以只使用伪造的:您自己的扩展PointF的子类

    public static class FakePointF extends PointF {
        FakePointF(float x, float y) {
            this.x = x;
            this.y = y;
        }
    }

但是在更复杂的测试中,您可能最终不得不模拟很多其他方法。

解决方案不是很不错:您需要针对仿真器或设备运行检测测试,或者转而使用Robolectric之类的工具,其中测试运行程序将为您替换“阴影”。

另请参见以下StackOverflow答案:android.graphics.Point:所有方法都是存根

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在Android中使用类构造函数

使用Gradle在Android中使用JUnit进行单元测试

Android Volley:无法解析构造函数jsonobjectrequest

无法解析构造函数(Android Intent)

Android无法解析构造函数意图

Android无法解析构造函数-静态片段

Android JUnit测试无法调用任何Android API?

您可以对使用Hilt构造函数注入的Android工人进行单元测试吗

使用JUNIT进行Android文件操作测试

如何使用junit测试Android sqlite?

使用Context.getApplicationContext()的Android JUnit测试

如何在 Kotlin 中 Room Entity 的构造函数中使用 Android 资源字符串

JUnit测试Android NullPointerException

JUnit测试Android NullPointerException

Dagger无法使用Dagger Android在ViewModel的构造函数上注入类型为interface的参数

Android JUnit测试,无法在assertThat中解析is(boolean)?

在Robolectric测试中使用Android KeyStore

在Android中使用Dagger生成的测试代码

使用Kotlin测试Android中的Lambda函数

Xamarin.Android上的JsonSerializationException'无法找到构造函数'

Android M + Retrofit + JSON:无法使字段构造函数可访问

Android:无法实例化类:无空构造函数

如何使用JUnit 5测试构造函数引发异常?

无法在Java中使用构造函数

android JUnit测试未运行

无法在Android JUnit 4已测试的测试中启动未绑定服务

无法在Android中使用视图绘制线条

无法在Android Studio中使用UsageStatsManager或UsageStats

无法在我的Android应用中使用StorageRefrence