0

我有一个简单的 Java 方法,我用它来测试来自 JSF 页面的输入。

public void validateDC(FacesContext context, UIComponent component, Object value) throws ValidatorException, SQLException
    {

        Double d;
        String s = value.toString().trim();

        if (s.length() > 10)
        {
                throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                        "  Value is too long! (18 digits max)", null));
        }

        try
        {
            d = Double.parseDouble(s);
            if (d < 0)
            {
                throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                        "  '" + d + "' must be positive number!", null));
            }
        }
        catch(NumberFormatException nfe) { d = null; }


        if (d != null)
        {


        }
        else
        {
            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                        s.isEmpty() ? "  This field cannot be empty!" : "  '" + s + "' is not a number!", null));
        }

    }

我对如何为这个验证器编写 JUnit 测试感兴趣?我可以简单地调用它并传递参数,但没有返回值。有哪些可能的解决方案?

4

2 回答 2

2

如果您使用的是 JUnit4,则可以使用:

@Test(expected=ValidatorException.class)
public void testValidatorException() {
 //call to trigger the exception   
 validateDC(...);
}
于 2013-01-21T15:54:57.387 回答
1

这是我编写的一些示例,旨在让您对如何测试您的方法有一个简单的了解。

@Test(expected = ValidatorException.class)
  public void shouldThrowExceptionWhenValueLengthIsGreaterThan10() throws Exception {
    Validaor validaor = new Validator();

    FacesContext context;
    UIComponent component;
    Object value;// <-- I don't know what value exactly is. But you have to create one with length less than 10  of its toString() value
    validaor.validateDC(context,component,value);

  }




  @Test
  public void shouldNotThrowExceptionWhenValueLengthIsLessThan10() throws Exception {
    Validaor validaor = new Validator();

    FacesContext context;
    UIComponent component;
    Object value;// create object with length more than 10 chars to of its toString() value
    validaor.validateDC(context,component,value);

  } 

希望这有帮助。

于 2013-01-21T16:07:39.630 回答