0
我有一個簡單的驗證來驗證客戶端不存在具有相同的屬性,只有驗證有2個選項: 1.如果滿足某些條件拋出驗證異常。 2.否則返回void。Junit無效驗證方法
像這樣:
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
}
}
了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
}
}
第二確認是可能發生的情況之一,是第二個驗證不必要的由於沒有斷言? 有沒有辦法驗證這個第二個條件?