Unit Testing
Last modified Thursday, 21-Nov-2024 14:02:44 UTC.
- Unit testing is a software testing method by which individual units of source code, often
methods and the methods they call, are tested to determine whether they are fit for use.
- A separate main or other method might be written with calls to the methods
being tested, and return values checked.
- This is a common practice, and there are several frameworks that automate this process.
- We will use the JUnit framework.
- The JUnit framework
- In IntelliJ ...
- Create a class, say Foo with a method doTheFoo.
Give the method package visibility by omitting the access modifier (see
the notes on package visibility).
- Right click project name, New directory srcTests
- Right click srcTests, Mark directory as "Test Sources Root"
- Right click on the class name Foo in the editor pane, to Generate ... Tests,
and select the methods you want to test.
This will create the test class and methods in srcTests.
- Note the @Test annotation and the import org.junit.jupiter.api.Test;
- Add import static org.junit.jupiter.api.Assertions.*
- Add code to test doTheFoo
- Ctl-Shift-R to run a test configuration.
Example:
JUnitPizzaCost.java
JUnitPizzaCostTests.java
- Read
more about writing
tests, particularly ...
-
Assertions, which test conditions in execution.
-
Assumptions, which support conditional test execution - a failed assumption results
in a test being aborted.
- Unit testing for Objects
Exercises
Exam Style Questions