简体   繁体   中英

How to unit test the GPS location in android using Robolectric?

I have an android app that gives the current location when button is tapped. I want to unit test this functionality . I'm using Robolectric . The issue is ,the system services are accessed in onCreate() method but not out of it. If that is the case,how can I access the device gps coordinates without calling the onCreate() method?

I tried calling the onCreate() from my testClass,but it gave me null pointer exception.

I am following the tutorial online http://ckarthik17-tech.blogspot.ca/2013/04/android-robolectric-unit-testing.html to perform the unit testing on location,but it doesnt work for me.

Here in the tutorial,the test class have the following piece of code,which rises the null pointer exception to me.

@Before
public void setUp() {
    mainActivity = new MainActivity();
    mainActivity.onCreate(null); // this is giving me null
    mainActivity.onCreate(new Bundle()); //I tired this too,still it gives me null
}

Robolectric creates the application differently. Try this:

mainActivity = Robolectric.buildActivity(MainActivity.class).create()
            .start().resume().get();

The NPE should go away, and the rest of the code from that tutorial should work just fine. Note that Alan Evans actually put almost the same snippet in the comments section of the post you cited.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM