从void方法测试Exception的BDDMockito 1.9.5

时间:2017-03-11 06:41:17

标签: java mockito

我的客户类看起来像

<tr>
  <td><input type="hidden" name="vendNameAddrSearch" class="vendNameAddrSearch" value="$vendorinfo">
    <input type="hidden" name="vendPhoneSearch" class="vendPhoneSearch" value="$res-phonenumber">
    <input type="hidden" name="vendEmailSearch" class="vendEmailSearch" value="$res-emailaddress">
    <button type="button" class="select-vendor">Select</button></td>
  <td>$res-vendorname</td>
  <td>$res-address1</td>
  <td>$res-address2</td>
  <td>$res-city</td>
  <td>$res-state</td>
  <td>$res-zip</td>
  <td>$res-country</td>
</tr>

和CustomerValidator检查年龄是否小于999如下

public class Customer {
    private String age;

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

}

我的CustomerValidatorTest类如下:

public class CustomerValidator {

    private final Pattern rxNumOnly3 = Pattern.compile("^[0-9]{1,3}$"); // only 3 digit

    public void validateCustomer(Customer customer){
        if (customer != null  && !rxNumOnly3.matcher(  customer.getAge() ).matches()){
            throw new RuntimeException("Age should be less than 3 digits");
        }
    }
}

我正试图在年龄为123岁时测试验证方法。 1234。 目前,测试用例是上述用例的通过。

任何人都可以提供一些输入,当测试失败时,年龄为1234&amp;当年龄为123时,测试通过了吗?

1 个答案:

答案 0 :(得分:0)

如果你想测试一些物体,你就不能嘲笑它。因此,最简单的方法是,您的测试应包含两种方法。第一种方法应该在年龄有效时检查验证通过。第二种方法应该检查当年龄无效时验证失败。

import org.junit.Assert;
import org.junit.Test;
import pl.mkorwel.spock.test.Customer;
import pl.mkorwel.spock.test.CustomerValidator;

public class CustomerValidatorTest {
    CustomerValidator customerValidator = new CustomerValidator();

    @Test
    public void shouldPassValidationWhenCustomerHasValidAge(){
        //given
        Customer customer = new Customer();
        customer.setAge("123");

        //when
        customerValidator.validateCustomer(customer);

        //then
        Assert.assertTrue(true);
    }

    @Test(expected = RuntimeException.class)
    public void shouldFailValidationWhenCustomerHasInvalidAge(){
        //given
        Customer customer = new Customer();
        customer.setAge("1234");

        //when
        customerValidator.validateCustomer(customer);
    }
}

如您所见,在这种情况下,您不需要Mockito

当然它只是样本,在这种情况下,你可以使用参数化测试。