-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAssertAnExceptionTest.java
More file actions
51 lines (46 loc) · 1.42 KB
/
AssertAnExceptionTest.java
File metadata and controls
51 lines (46 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package io.github.walterinsh.basic;
import io.github.walterinsh.Method;
import org.testng.annotations.Test;
/**
* How to assert methods which expected throws an exception?
*
* "expectedExceptions" is the answer!
*
* Created by Walter on 11/8/15.
*/
public class AssertAnExceptionTest {
/**
* If not throwing an exception means this method works fine.
* Just invoke it!
*
* (But to most of situations this is not good enough.)
* @throws Exception
*/
@Test
public void assertCorrectUse() throws Exception {
Method.onlyAcceptPositiveNum(1);
}
/**
* Sometimes we offer an incorrect parameter to a method to see if it can
* throws an exception as we expected.
*
* Just do it this way.
* @throws Exception
*/
@Test(expectedExceptions = IllegalArgumentException.class)
public void expectAnException() throws Exception {
Method.onlyAcceptPositiveNum(-1);
}
/**
* Sometimes asserting an exception is also not specific enough. Because
* a method could throw an exception with different reasons. Asserting the
* message is necessary.
*
* @throws Exception
*/
@Test(expectedExceptions = IllegalArgumentException.class,
expectedExceptionsMessageRegExp = "negative num is not acceptable")
public void expectAnExceptionWithAMessage() throws Exception {
Method.onlyAcceptPositiveNum(-1);
}
}