views:

42

answers:

2

Hi all,

I am writing a Junit(4.x) test to test what happens when the web application is down.

When I hit the url in the browser, I get a message saying "Connection refused".

I am unsure about what to check for in the assert statements.

Do I check the header for this message? -- urlConnection.getResponseMessage() or

just say (expected = java.net.ConnectException) before the test case. I feel the latter is not specific enough.

EDIT: Right now, I'm using a combination of (expected = java.net.ConnectException) and assertEquals(502, urlConnection.getResponseCode). The test is passing.

Thanks, Pratyusha.

+2  A: 

First of all, your unit tests should not depend so much on external entities. What you describe is rather an integration test.

In a classic unit test, you could set up this scenario by using e.g. a mock HttpUrlConnection. This can be programmed to throw an exception from the desired method call. If you are not happy by simply acknowledging the type of exception thrown, you can always catch it within the test method, then assert the response message or whatever you are interested in.

However, from your post it is not clear to me what are you actually testing: a web client which depends on a server? A web app which calls another web app? Different tests may be adequate for different scenarios.

Péter Török
I agree it is an integration test. Sadly, I have no choice here but to use Junit.
Pratyusha
True. For such cases, Pratyusha should probably be using JMeter or HTTPUnit.
pavanlimo
@Pratyusha, you can implement integration tests using JUnit (although there are indeed better choices for the task you describe - I would add Selenium to the list). However, it is good to be aware of the difference between unit and integration tests. They typically have different resource requirements and usage patterns.
Péter Török
Peter: I understand your point and agree with you. But this is a requirement and such, and I *must* do it in JUnit. Atleast for now. Meanwhile, I'm also exploring Selenium/JMeter/HTTPUnit. Thanks.
Pratyusha
@Pratyusha, I understand. I didn't mean to say you should disobey requirements - sorry if my comment was misunderstandable.
Péter Török
Peter: No problem. I wasn't clear enough earlier I guess :)
Pratyusha
A: 

Integration tests in junit are fine. Many widely used open source projects use this approach. See CXF or Arquillian for examples of this approach.

For your question... you need to decide what the desired behaviour is and then test for this.

For example in this case you probably want to test the response code the server is returning. Or if "connection refused" really is desired behaviour then testing for (expected = java.net.ConnectException) should be sufficient.

Pablojim