Question

I have a simple validation to verify that an Client does not exists with the same attributes, the validation only that has 2 options: 1. throw an validation exception if certain condition is met. 2. Return void otherwise.

Like this:

public class ClientValidator {
   private ClientFinder clientFinder;
   protected void validate(final Client client) throws ValidationException
   {
        final Client existingClient = clientFinder.getClientByAttributes(client.getAttr1(),
        client.getAttr2());
        if (existingClient != null && ! existingClient.getId().equals(client.getId()))
        {
            throw new ValidationException("Client Exists with the same attributes"));
        }
   }
   //getters and setters

}    
}

The Junit:

@UnitTest
@RunWith(MockitoJUnitRunner.class)
public class ValidatorTest
{
    private ClientValidator validator;

    @Mock
    private ClientFinder clientFinder;
    private Client existingClient;
    private Client newClient;
    private static final String ATTR1 = "ATTR1";
    private static final String ATTR2 = "ATTR2";

    @Before
    public void setup()
    {
        existingClient = new Client("ID1", ATTR1, ATTR2);
        newClient = new Client("ID2", ATTR1, ATTR2);


        validator = new ClientValidator();
        validator.setClientFinder(clientFinder);
    }

    @Test(expected = ValidatorException.class)
    public void testCreatingNewClient() throws ValidationException
    {
        //the service will find other Client than the one being created
        Mockito.when(clientFinder.getClientByAttributes(ATTR1, ATTR2)).thenReturn(existingClient);
        validator.onValidate(newClient);
    }



    @Test()
    public void testModifyExistingClient() throws ValidationException
    {
        //the service will find the same Client being modified
        Mockito.when(clientFinder.getClientByAttributes(ATTR1, ATTR2)).thenReturn(newClient);
        validator.onValidate(newClient); //No exception should be thrown
    }


}

The second validation is one of the cases that might happen, is the second validation unneccessary due to the fact that there is no assertion? Is there a way to validate this second condition?

Was it helpful?

Solution

The test as you've written it is fine. There is no need for an "assert". The fact that execution reaches the bottom of the test is enough to make it "green". You've already got a comment to that effect in your test, and by all means leave this in, just to make it clear what's going on. But please don't add a meaningless "assert" to your test.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top