Member-only story
A slightly different way to do Boolean assertions in JUnit
In my opinion, the most useful assertion in JUnit is assertEquals()
. Once in a while, though, assertTrue()
comes in handy. Its single parameter form takes a Boolean, its 2-parameter form takes an assertion message and a Boolean (in JUnit 5, the Boolean goes first, before the assertion message).
I’m going to use a toy example here, since I just want to focus on the syntax. Create a Refrigerator
class somewhere in Source Packages (don’t write any explicit constructors), and a corresponding RefrigeratorTest
class in Test Packages. In the test class, put in the following:
@Test
public void testFridgeTempProperRange() {
Refrigerator fridge = new Refrigerator();
double temperature = fridge.getTemperature();
assertTrue("Temp too cold", temperature > 10.0);
assertTrue("Temp too high", temperature < 40.0);
}
Degrees are in Fahrenheit, but we’re not too concerned about that detail for this toy example.
Write getTemperature()
so it gives a temperature outside the proper range. Run the test. It should fail. If the temperature is too cold, your console might show something like this:
Testcase: testFridgeTempProperRange(basicexercises.RefrigeratorTest): FAILED
Temp too cold
junit.framework.AssertionFailedError…