我有一个简单的验证来验证客户端是否存在具有相同属性,验证只有2个选项: 1.如果满足某些条件,则抛出验证异常。 2.否则返回无效。
像这样:
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
}
}
第二次验证是可能发生的情况之一,是否由于没有断言而需要进行第二次验证? 有没有办法验证第二个条件?
答案 0 :(得分:1)
你写的测试很好。不需要“断言”。执行到达测试底部的事实足以使其“绿色”。你已经在测试中对这个效果做了评论,并且一定要把它放进去,只是为了清楚说明发生了什么。但请不要在测试中添加无意义的“断言”。