使用Robolectric.buildAttributeSet()进行单元测试会导致NullPointerException

时间:2017-11-24 22:03:19

标签: android junit4 robolectric

我有一个PercentView类,我正在尝试设置一个测试,我想验证它是否被绘制到正确的大小。我有一个简单的酒吧,但现在我想在它上面有一个图像/图标,这是一个可绘制的(实际上是矢量)。

关于此的一些注意事项:

  • 我有一个名为app_enabled.xml的可绘制文件(矢量),main\res\drawable\app_enabled.xml
  • 我正在使用Robolectric 3.5.1
  • 我看过Robolectric团队在这里测试的代码:Robolectric example: ViewStubTest.java

我已经宣布了样式:

<declare-styleable name="PercentageView">
    <attr name="image" format="integer" />
</declare-styleable>

观点:

public class PercentageView extends View {
    private int _activeColor;
    private int _barBackgroundColor;
    private float _barHeight;
    private Drawable _icon;
    private Paint _barBackgroundPaint;
    private Paint _barActivePaint;
    private int _percent;

    public PercentageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        TypedArray args = context.getTheme().obtainStyledAttributes(
                attrs,
                R.styleable.PercentageView,
                0,
                0);

        try {
            _icon = args.getDrawable(R.styleable.PercentageView_image);

        } finally {
            args.recycle();
        }

        init();
    }
}

现在测试:

@RunWith(RobolectricTestRunner.class)
public class PercentageViewTests {
    private ShadowCanvas _shadowCanvas;
    private int _width;
    private int _height;
    private float _expectedPercentWidth;
    private int _thePercent;
    private Canvas _canvas;

    private PercentageView SetUpView(int width, int height, int percent, boolean useIcon) {
        ShadowApplication app = shadowOf(RuntimeEnvironment.application);

        //Attempt to pass in the icon, if useIcon is true
        AttributeSet attr = useIcon ? Robolectric.buildAttributeSet()
            .addAttribute(R.styleable.PercentageView_image, "@drawable/app_enabled") //NullPointerException here
            .build() : null;

        PercentageView view = new PercentageView(app.getApplicationContext(), attr);
        view.setLayoutParams(new ViewGroup.LayoutParams(width, height));
        view.setPercent(percent);

        return view;
    }

    @Before
    public void setup() {
        Random random = new Random(10);
        _width = random.nextInt(100);
        random.setSeed(101);
        _height = random.nextInt(200);

        random = new Random(0);
        _thePercent = random.nextInt(100);
        _expectedPercentWidth = _width * _thePercent / 100;

        _canvas = new Canvas();
        _shadowCanvas = shadowOf(_canvas);
    }

    @Test
    public void ShouldHaveIcon() {
        PercentageView view = SetUpView(_width, _height, _thePercent, true);
        view.onDraw(_canvas);

        assertThat(_shadowCanvas.getRectPaintHistoryCount(), is(equalTo(3)));
    }
}

非常悲伤,堆栈痕迹:

java.lang.NullPointerException
at org.robolectric.Robolectric$AttributeSetBuilder.addAttribute(Robolectric.java:161)
at myorg.controls.PercentageViewTests.SetUpView(PercentageViewTests.java:41)
at myorg.controls.PercentageViewTests.ShouldHaveIcon(PercentageViewTests.java:140)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.robolectric.RobolectricTestRunner$HelperTestRunner$1.evaluate(RobolectricTestRunner.java:523)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.robolectric.internal.SandboxTestRunner$2.evaluate(SandboxTestRunner.java:226)
at org.robolectric.internal.SandboxTestRunner.runChild(SandboxTestRunner.java:108)
at org.robolectric.internal.SandboxTestRunner.runChild(SandboxTestRunner.java:35)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.robolectric.internal.SandboxTestRunner$1.evaluate(SandboxTestRunner.java:62)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:131)

2 个答案:

答案 0 :(得分:1)

尝试将R.styleable.PercentageView_image替换为R.attr.image

似乎addAttribute()的第一个参数需要是attr的res,而不是stylable

答案 1 :(得分:0)

这是迟来的回应,但是,今天我也为此感到挣扎。

我想创建一个自定义的HelpLinkBut​​ton,它接受一个Url作为xml中的属性参数。

attrs.xml:

    <declare-styleable name="HelpLinkButton">
        <attr name="Url" format="string|reference" />
    </declare-styleable>

HelpLinkBut​​ton

class HelpLinkButton @JvmOverloads constructor(
    context: Context?, 
    attrs: AttributeSet?, 
    defStyleAttr: Int
) : AppCompatButton(context, attrs, defStyleAttr) {

    var uri: Uri = Uri.EMPTY

    init {
        super.setOnClickListener {}
        context?.let { _context ->
            _context.obtainStyledAttributes(attrs, R.styleable.HelpLinkButton, defStyleAttr, 0)?.let { typedArray ->
                if (typedArray.hasValue(R.styleable.HelpLinkButton_Url)) {
                    typedArray.getResourceId(R.styleable.HelpLinkButton_Url, -1).let {
                        if (it != -1) {
                            uri = Uri.parse(_context.getString(it))
                        } else {
                            typedArray.getString(R.styleable.HelpLinkButton_Url)?.let {
                                uri = Uri.parse(it)
                            }
                        }
                    }
                }
                typedArray.recycle()
            }
        }
    }

    override fun setOnClickListener(l: OnClickListener?) {}
}

test.kt


@RunWith(AndroidJUnit4::class)
class HelpLinkButtonTest {

    @Test
    fun inits_with_string_attr() {
        val builder = Robolectric.buildAttributeSet()
        val url = "http://example.com"
        builder.addAttribute(R.attr.Url, url)

        val button = HelpLinkButton(
                context = ApplicationProvider.getApplicationContext(),
                attrs = builder.build(),
                defStyleAttr = 0
        )

        assertThat(button.uri.toString()).isEqualTo(url)
    }

    @Test
    fun inits_with_resource_attr() {
        val builder = Robolectric.buildAttributeSet()
        builder.addAttribute(R.attr.Url, "@string/upgrade_now_help_url")

        val button = HelpLinkButton(
                context = ApplicationProvider.getApplicationContext(),
                attrs = builder.build(),
                defStyleAttr = 0
        )


       assertThat(button.uri.toString()).isEqualTo("https://dropbit.app/upgrade")
    }


}

我在期望值的末尾添加了/,以显示attrs的输出失败。

测试输出

[Robolectric] com.coinninja.coinkeeper.view.button.HelpLinkButtonTest.inits_with_resource_attr: sdk=28; resources=BINARY
Called loadFromPath(/system/framework/framework-res.apk, true); mode=binary sdk=28

expected: https://dropbit.app/upgrade/
but was : https://dropbit.app/upgrade
Expected :https://dropbit.app/upgrade/
Actual   :https://dropbit.app/upgrade
<Click to see difference>


    at com.coinninja.coinkeeper.view.button.HelpLinkButtonTest.inits_with_resource_attr(HelpLinkButtonTest.kt:40)

[Robolectric] com.coinninja.coinkeeper.view.button.HelpLinkButtonTest.inits_with_string_attr: sdk=28; resources=BINARY
WARN: No type identifier when getting name for resource number 0x01000000

expected: http://example.com/
but was : http://example.com
Expected :http://example.com/
Actual   :http://example.com
<Click to see difference>


    at com.coinninja.coinkeeper.view.button.HelpLinkButtonTest.inits_with_string_attr(HelpLinkButtonTest.kt:26)


Process finished with exit code 255