dom*_*m96 6 java junit android unit-testing
我在尝试编写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);
}
}
Run Code Online (Sandbox Code Playgroud)
在全新的Android项目中运行此测试会导致声明失败:
java.lang.AssertionError:
Expected :5.0
Actual :0.0
Run Code Online (Sandbox Code Playgroud)
我在调查此问题时发现的一件事是x
直接分配给PointF实例的字段确实有效。
那么这是什么问题呢?为什么构造函数不能正确设置字段?我应该如何测试使用PointF Android类的类?
参见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;
}
}
Run Code Online (Sandbox Code Playgroud)
但是在更复杂的测试中,您可能最终不得不模拟很多其他方法。
解决方案并不完美:您需要针对仿真器或设备运行检测测试,或者转而使用Robolectric之类的工具,其中测试运行程序将为您替换“ 阴影 ”。
另请参见以下StackOverflow答案:android.graphics.Point:所有方法都是存根。
归档时间: |
|
查看次数: |
853 次 |
最近记录: |