简体   繁体   中英

How to unit test with actual HttpURLConnection in android?

I am writing unit tests/integration tests that invoke class library that uses HttpsURLConnection objects. Many times whilst invoking methods on the connection objects through the unit tests, like addRequestProperty , setDoOutput , setRequestMethod I get exceptions like java.lang.IllegalStateException: Already connected . The behaviour is most likely due to following in the gradle as default values are returned.

testOptions {
    unitTests.returnDefaultValues = true
}

See http://tools.android.com/tech-docs/unit-testing-support for more details

The same code works fine in the App. Is there a way to actually use the real HttpsURLConnection object while testing?

You can use libraries to mock requests and responses. I recommend this one: MockWebServer .

Edit : After re-reading your question, it looks like you want to use HttpsURLConnection in your unit tests. The problem of trying to use a class from the Android SDK in your Unit test means that your test becomes an instrumentation test, and that means that it must run on the device/emulator.

If you want an example of integration instrumentation tests, take a look at this great example.

As HttpsURLConnection is also in the Java JDK bundle, if you use that class (import javax.net.ssl) you may have a change of not using any Android classes so you could run your test as a local unit test in your JVM (not the device/emulator).

If you want to understand a bit better the difference between instrumented and local unit tests, read this blog post.

Since HttpsURLConnection is part of android one way to test would be using Android Instrumented Tests as described at http://developer.android.com/training/testing/start/index.html . This starts an AVD or a real device and runs tests there.

Make sure you set the permission in AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>

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