0

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?

resp78
  • 1,414
  • 16
  • 37
  • It looks like I have to write the test cases as described at http://developer.android.com/training/testing/unit-testing/instrumented-unit-tests.html as HttpsURLConnection is part of android. – resp78 Apr 04 '16 at 12:47

2 Answers2

1

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.

Yair Kukielka
  • 10,686
  • 1
  • 38
  • 46
0

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"/>

resp78
  • 1,414
  • 16
  • 37