Categories
discuss

Android PointF constructor not working in JUnit test

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; …

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);
    }
}

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

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

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

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?

Answer

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

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.

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.

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.

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

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..