... | ... | @@ -2,6 +2,26 @@ |
|
|
|
|
|
### Using NanoHttpd to isolate network call testing
|
|
|
|
|
|
|
|
|
### Simple synchronous network call
|
|
|
```java
|
|
|
public void testSimpleEcho() throws Exception {
|
|
|
URL url = new URL("http://localhost:7078/echo/hello_world");
|
|
|
String responseContents = "";
|
|
|
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
|
|
|
try {
|
|
|
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
|
|
|
java.util.Scanner s = new java.util.Scanner(in).useDelimiter("\\A");
|
|
|
if (s.hasNext()) {
|
|
|
responseContents = s.next();
|
|
|
}
|
|
|
} finally {
|
|
|
urlConnection.disconnect();
|
|
|
}
|
|
|
assertEquals("hello_world", responseContents );
|
|
|
}
|
|
|
```
|
|
|
|
|
|
Setup
|
|
|
#### Gradle
|
|
|
if you are only using nanohttp for testing then use testCompile, otherwise compile
|
... | ... | @@ -156,26 +176,6 @@ mstevens@lt-mstevens-mac2:androidTest$ tree |
|
|
|
|
|
```
|
|
|
|
|
|
### Simple synchronous network call
|
|
|
```java
|
|
|
public void testSimpleEcho() throws Exception {
|
|
|
URL url = new URL("http://localhost:7078/echo/hello_world");
|
|
|
String responseContents = "";
|
|
|
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
|
|
|
try {
|
|
|
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
|
|
|
java.util.Scanner s = new java.util.Scanner(in).useDelimiter("\\A");
|
|
|
if (s.hasNext()) {
|
|
|
responseContents = s.next();
|
|
|
}
|
|
|
} finally {
|
|
|
urlConnection.disconnect();
|
|
|
}
|
|
|
assertEquals("hello_world", responseContents );
|
|
|
}
|
|
|
```
|
|
|
|
|
|
|
|
|
### Using a Semaphore to test network responses
|
|
|
Semaphore is an easy way to deal with async calls. A semaphore tracks a permit count, release( ) increments the permit count, aquire( ) decrements the permit if it was non zero.
|
|
|
|
... | ... | |