Android PointF构造函数无法在JUnit测试中使用 [英] Android PointF constructor not working in JUnit test

查看:88
本文介绍了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?

推荐答案

请参见当运行单元测试时,您正在使用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测试中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆