给定这样一个class。
Person.java public class Person { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { if (age < 0 ) { throw new IllegalArgumentException("age is invalid"); } this.age = age; } } |
我们来测试setAge方法。
Try-catch 方式 @Test public void shouldGetExceptionWhenAgeLessThan0() { Person person = new Person(); try { person.setAge(-1); fail("should get IllegalArgumentException"); } catch (IllegalArgumentException ex) { assertThat(ex.getMessage(),containsString("age is invalid")); } } |
这是最容易想到的一种方式,但是太啰嗦。