1.4. Java Unit Testing¶
1.4.1. Objectives¶
Upon completion of this module, students will be able to:
Review the basics of a java class including fields, constructors, methods, parameters, and use of the keyword this
Review debugging code and code coverage
Implement variations for JUnit assert statements
1.4.2. Interactive: Introduction to Hokie Class¶
In this discussion we will be revisiting good testing practices with an example class called “Hokie Class”.
Follow Along, Practice and Explore
Hokie.java
- Download to run and explore the java file (see below) from the video on your own in eclipse. You may download the standalone *.java file for this example. To run the standalone *.java file you will need to
create a new Eclipse project, then
create a package within the project called “example” (the package named at the top of the class MUST match the package the file is placed in within the Eclipse project), and finally
download and import the standalone *.java file(s) to the created package.
1.4.3. Checkpoint 1¶
1.4.4. Intro to Hokie Class JUnit Testing¶
1.4.4.1. A Note about Assert Statements¶
So far in the course when we want to test that a piece of code acted the way we wanted, we’d run a statement like:
assertThat(<something we want to check>).isEqualTo(<expected value>);
This is a more modern style that’s intended to be more readable. However, there is a different form of syntax you can use to create assertions:
assertEquals(<expected value>, <something we want to check>);
This second kind of assert statement is more commonly used today, but it can be tricky to use correctly. When using asserEquals
, it can be easy to put the value we want to check first and the expected value second.
For example, say we wanted to check that a variable x
was equal to 5.
int x = 4;
assertEquals(x, 5);
Writing like this would be syntactically correct, but potentially confusing because the failure message would read “Expected [4] but got [5]”. In reality, we were expecting 5 but got 4.
Videos in the second half of the course will be using this second, more commonly used syntax. You can continue to use either version. Below, is a table of assertions in both styles.
Task |
AssertThat Style |
Traditional Style |
Notes |
---|---|---|---|
Checking that |
|
|
While the new style has a |
Check that a double |
|
|
|
Checking that |
|
|
|
Checking that |
|
|
|
Checking that |
|
|
|
Checking that |
|
|
|
Checking two object variables refer to the same space in memory |
|
|
1.4.5. Interactive: Hokie Class JUnit Testing¶
Follow Along and Engage
JavaUnitTesting.pdfDownload the slides corresponding to the video. Take notes on them as you watch the video, practice drawing diagrams yourself!