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

编程入门 行业动态 更新时间:2024-10-26 11:13:33
本文介绍了Android PointF构造函数无法在JUnit测试中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I have just stumbled on this while trying to write a JUnit test. Admittedly this is my first unit test in JUnit, but I do find the behaviour very puzzling.

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项目中运行此测试会导致声明失败:

Running this test in a brand new Android Project results in an assertion failure:

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

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

One thing I found out while investigating this problem is that assigning to the PointF instance's x field directly does work.

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

So what is the problem here? Why doesn't the constructor set the fields properly? and how should I be testing classes which use the PointF Android class?

推荐答案

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

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

When you run unit tests, you are using a dummy version of the android jar. Typically you will see "Method ... not mocked."exceptions, but since you are directly accessing public fields, these are simply default values.

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

Depending on your requirements, you could just use a fake: your own subclass extending PointF

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

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

but in a more complex test you'll probably end up having to mock a whole lot of other methods.

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

The solution isnt pretty: you need to run instrumented tests against an emulator or device, or move to using something like Robolectric where the test runner will substitute 'shadows' for you.

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

Also see this StackOverflow answer: android.graphics.Point: all methods are stubs.

更多推荐

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

本文发布于:2023-10-31 06:42:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545321.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   测试中   Android   PointF   JUnit

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!