Browse Source

Use Expected Exception Rule

Use an @Rule instead of @Test(expected=…)
Colin Mullikin 9 years ago
parent
commit
22ea1a5b68

+ 10
- 7
exercises/phone-number/src/example/java/PhoneNumber.java View File

11
     }
11
     }
12
 
12
 
13
     private String normalize(String number) {
13
     private String normalize(String number) {
14
-        if(number.length() == 11 && number.startsWith("1")) {
15
-            number = number.substring(1, number.length());
14
+        if(number.length() > 11 || number.length() < 10){
15
+            throw new IllegalArgumentException("Number must be 10 or 11 digits");
16
         }
16
         }
17
 
17
 
18
-        final boolean numberIsValid = (number.length() == 10);
19
-
20
-        if(!numberIsValid) {
21
-            throw new IllegalArgumentException();
22
-        }
18
+        if(number.length() == 11){
19
+            if(number.startsWith("1")){
20
+                number = number.substring(1, number.length());
21
+            }
22
+            else{
23
+                throw new IllegalArgumentException("Can only have 11 digits if number starts with '1'");
24
+            }
25
+        } 
23
         
26
         
24
         return number;
27
         return number;
25
     }
28
     }

+ 12
- 4
exercises/phone-number/src/test/java/PhoneNumberTest.java View File

1
 import org.junit.Test;
1
 import org.junit.Test;
2
 import org.junit.Ignore;
2
 import org.junit.Ignore;
3
+import org.junit.Rule;
4
+import org.junit.rules.ExpectedException;
3
 
5
 
4
 import static org.junit.Assert.*;
6
 import static org.junit.Assert.*;
5
 
7
 
6
 public class PhoneNumberTest {
8
 public class PhoneNumberTest {
7
 
9
 
10
+    @Rule
11
+    public ExpectedException expectedException = ExpectedException.none();
8
 
12
 
9
     @Test
13
     @Test
10
     public void cleansNumber() {
14
     public void cleansNumber() {
39
     }
43
     }
40
 
44
 
41
     @Ignore
45
     @Ignore
42
-    @Test(expected = IllegalArgumentException.class)
46
+    @Test
43
     public void invalidWhenOnly11Digits() {
47
     public void invalidWhenOnly11Digits() {
44
-        final String actualNumber = new PhoneNumber("21234567890").getNumber();
48
+        expectedException.expect(IllegalArgumentException.class);
49
+        expectedException.expectMessage("Can only have 11 digits if number starts with '1'");
50
+        new PhoneNumber("21234567890").getNumber();
45
     }
51
     }
46
 
52
 
47
     @Ignore
53
     @Ignore
48
-    @Test(expected = IllegalArgumentException.class)
54
+    @Test
49
     public void invalidWhen9Digits() {
55
     public void invalidWhen9Digits() {
50
-        final String actualNumber = new PhoneNumber("123456789").getNumber();
56
+        expectedException.expect(IllegalArgumentException.class);
57
+        expectedException.expectMessage("Number must be 10 or 11 digits");
58
+        new PhoneNumber("123456789").getNumber();
51
     }
59
     }
52
 
60
 
53
     @Ignore
61
     @Ignore