Reputation: 1534
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?
Upvotes: 0
Views: 2074
Reputation: 1534
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"/>
Upvotes: 0
Reputation: 11406
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.
Upvotes: 1