tags:

views:

10

answers:

1

Hi Guys,

I am writting unit tests for various bean property constraints. For most of the constraints such is field length , format of the field and whether a field is null or not, i am able to test using the JSR303 validation API. My question is, how do i write a unit test for this constraint: 'The field username of entity User must be unique' . I am a java developer so would appreciate a java based solution though any answer is much welcome.

Kind regards.

A: 

Try to store two User entities with equal username fields, and check, that adequate exception is thrown.

Exception checking may be easily done with junit with the help of "expected" parameter of @Text annotation:

 @Test(expected=MyException.class)
 public void testMyException() {

See details here: http://junit.sourceforge.net/doc/faq/faq.htm#tests_7

Kel
thanks Kel. How do i assert that an exception is thrown? This also means that the test for checking the uniqueness will fail if the code for saving is not working. is it acceptable in unit testing?
joshua
Kel. I have learnt how to assert that an exception was thrown. I think i will use that approach . I also dont see the point of testing the method for persisting the entity because it just delegates to the entity manager. Thanks your your prompt response.
joshua
I've updated the answer with exception checking details. Test for checking uniqueness will FAIL, if the code of saving second user with already existent username PASSES (this means, that uniqueness validation DOES NOT work as expected). I think, it's acceptable in unit testing, and there are means for testing that.
Kel