Reputation: 65
I have an application that supports a few outbound web services. I am using HttpClient and I need to add a service time out because one of the external URLs that I am accessing takes a long time to respond (at times). I am trying to add a few junit test cases to make sure my timeout is working properly. I have something like this where the specified timeout value is little more than the configured socket timeout -
@Test (timeout=6000)
public void testTimeOut() {
notifier.performGetonUrl(getTestUrl());
}
I don't feel its a good one. Are there better tests I could use?
Upvotes: 3
Views: 3885
Reputation: 1313
If you are looking to write a true isolation unit test of your code then I agree that your test isn't appropriate. If you are looking to write more of an integration test then your approach is fine.
For my isolation junits I create them so that they only test the class under test. I use EasyMock to mock out all collaborating classes. So in this case I would create a mock for httpClient. I would set up a test where the mock throws the exception, and then assert that the class under test handles the exception as expected. The code snippets below may give you an idea of what I mean.
private DefaultHttpClient httpClient;
private ClassUnderTest classUnderTest;
@Before
public void setUpTest() {
httpClient = createMock(DefaultHttpClient.class);
@Test
public void performARequestThatThrowsAnIOException() {
expect(httpClient.execute(post)).andThrow(iOException);
replayAll();
try {
classUnderTest.executeMethodUnderTest();
fail("This test should throw an IOException.");
} catch (IOException e){
verifyAll();
}
The above assumes that the method in the class under test throws the exception. If the exception is caught then you would write the above differently.
Upvotes: 1