【问题标题】:Junit for a void validation method用于无效验证方法的 Junit
【发布时间】:2014-04-07 14:10:17
【问题描述】:

我有一个简单的验证来验证不存在具有相同属性的客户端,验证只有两个选项: 1. 如果满足某些条件,则抛出验证异常。 2. 否则返回 void。

像这样:

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
    }


}

第二次验证是可能发生的情况之一,由于没有断言,第二次验证是不必要的吗? 有没有办法验证第二个条件?

【问题讨论】:

    标签: java validation junit mockito void


    【解决方案1】:

    您编写的测试很好。不需要“断言”。执行到达测试底部的事实足以使其“绿色”。你已经在你的测试中得到了关于这个效果的评论,并且一定要把它留在里面,只是为了弄清楚发生了什么。但请不要在您的测试中添加无意义的“断言”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-16
      • 2018-08-10
      • 2019-04-06
      相关资源
      最近更新 更多