Not only do we need to test a program for situations when things go right, we also need to make sure we handle things correctly when they go wrong. Specifically, we need to verify that code throws exceptions as expected. A typical example might be gracefully handling an index out of bounds exception when your program uses arrays or arrayLists.
- [Narrator] Not only do we need to…test a program for situations when things go right,…we also need to make sure we handle things correctly…when they go wrong.…Specifically, we need to verify that the code…throws the exceptions as we expect them to be thrown.…Let's take a look at some examples.…A typical example might be gracefully handling…an index out of bounds exception…when your program uses arrays or array lists.…I've already created an exception handling test program,…and let me scroll down a little bit…and show you the test that I have set up.…
So on line 33 I have my @Test.…Now in order to test for a specific exception,…we actually can add to the right of that in parenthesis…our expected value.…So I say expected equals…index out of bounds exception dot class,…and then on line 34 in my test main…I create a new array list object,…and then I try and get the element at position zero,…but I just created the new array list…and I have not instantiated any objects at all yet.…
So that would return an index out of bounds,…
- What is JUnit?
- Comparing values with assertions
- Using JUnit with different Java IDEs
- Creating basic unit tests
- Testing for exception handling
- Creating parameterized tests