gpt4 book ai didi

java - Android PointF 构造函数在 JUnit 测试中不起作用

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:54:01 26 4
gpt4 key购买 nike

我在尝试编写 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

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

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

最佳答案

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

当您运行单元测试时,您使用的是 android jar 的虚拟版本。通常您会看到“Method ... not mocked.”异常,但由于您直接访问公共(public)字段,因此这些只是默认值。

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

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

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

解决方案并不完美:您需要针对模拟器或设备运行插桩测试,或者转而使用 Robolectric 之类的工具,其中测试运行器将替换“shadows”。 ' 给你。

另见 StackOverflow 答案:android.graphics.Point: all methods are stubs .

关于java - Android PointF 构造函数在 JUnit 测试中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34010251/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com