Skip to content

Instantly share code, notes, and snippets.

@leviwilson
Created September 4, 2012 16:24
Show Gist options
  • Save leviwilson/3623053 to your computer and use it in GitHub Desktop.
Save leviwilson/3623053 to your computer and use it in GitHub Desktop.
Mock HttpURLConnection Example
package com.example.robolectric;
import static com.xtremelabs.robolectric.Robolectric.shadowOf;
import static org.mockito.Mockito.verify;
import java.io.IOException;
import java.net.*;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import android.app.Activity;
import android.os.Bundle;
import com.xtremelabs.robolectric.RobolectricTestRunner;
@RunWith(RobolectricTestRunner.class)
public class HttpUrlActivityTest {
@Mock
HttpURLConnection mockHttpConnection;
HttpUrlActivity activity;
public class HttpUrlActivity extends Activity {
private HttpURLConnection httpConnection;
// this would be in the for real application
public HttpUrlActivity() throws MalformedURLException, IOException {
this((HttpURLConnection) new URL("http://someurl.com/").openConnection());
}
// this is how we inject the mock in our test
public HttpUrlActivity(final HttpURLConnection httpConnection) {
this.httpConnection = httpConnection;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
try {
httpConnection.setRequestMethod("GET");
} catch (ProtocolException e) {
throw new RuntimeException(e);
}
super.onCreate(savedInstanceState);
}
}
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
activity = new HttpUrlActivity(mockHttpConnection);
}
@Test
public void itCanTestHttpURLConnectionStuff() throws ProtocolException {
shadowOf(activity).create();
verify(mockHttpConnection).setRequestMethod("GET");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment