Testing server with JUnit
I would like to test my REST server with JUnit
. Each test sends an HTTP request to the server and checks the response against the list of the elements开发者_StackOverflow中文版 expected to appear in the response.
So, the testing procedure looks as follows:
for each request in test requests send request and receive response assert the response is ok for each element in the expected elements test if the element exists in the response
How would you implement it with JUnit
?
I would use the @BeforeClass
method in your JUnit class to grab the latest version of your server and start it up (choosing an appropriate port and so on). Similarly @AfterClass
could be used to programatically shut the server down. Doing this automatically is important as otherwise you'll have to remember to have the latest version of your server running continously.
I've assumed that the tests don't change any data in the server. If they do, then you should probably use @Before
and @After
, but bear in mind this'll cause your server to start/stop for each test and that could make the tests take an unreasonably long time.
Once you've got that framework in place, writing the test itself should be simple.
You could also write this as a "proper" unit test by ensuring that your RESTful API is exposed as just a plain Java API, isolated from the networking layer. This would be much quicker to run and (hopefully if your network layer is thin enough) pick up much of the same possible bugs.
精彩评论