1. Testing with JUnit

Prerequisites

  • JUnit and AssertJ in the classpath

  • Understanding of test-driven development

  • JUnit 5

  • AssertJ

Data types used in this chapter:

1.1. JUnit

1.1.1. Broken again ⭐

Apache Commons Lang (https://commons.apache.org/proper/commons-lang/) is a library of open source Java components developed by the Apache Software Foundation. It contains classes and methods that provide commonly used functionality that is not part of the Java Standard Edition.

Task:

  • Download commons-lang3-3.13.0-src.zip. Unpack the archive. Import it as a Maven project into the IDE.

  • Run all test cases in the IDE. Run all test cases via Maven, you can use mvn test for this. There may be errors, they can be ignored.

  • Get an impression of the class Fraction.java via the Javadoc Fraction Javadoc. Think about how test cases should look.

  • Take a look at the implementation of the test class FractionTest.java. Which JUnit techniques are recognizable?

1.2. AssertJ

AssertJ (https://assertj.github.io/doc/) is a library for Fluent Assertions for Java. AssertJ can be used to write concise, readable tests by expressing assertions in an intuitively understandable way. If a test fails, AssertJ generates informative error messages.

1.2.1. Getting Started with AssertJ ⭐

Task:

1.2.2. Test-first with monetary amounts ⭐

Task:

  1. Create a new class com.tutego.money.MonetaryAmount. It should store a monetary amount to two decimal places. The object is immutable and must be thread-safe and also Serializable. Use the following incomplete but compilable template:

    public class MonetaryAmount {
    
     private MonetaryAmount() { }
    
     // create immutable MonetaryAmount objects by factory method
     public static MonetaryAmount of( double value ) { return null; }
    
     // return the value
     public double value() { return 0; }
     public String toString() { return ""; }
    
     // MonetaryAmount objects should be able to be compared with equals(Object o)
     public boolean equals( Object o ) { return false; }
    
     //
     public MonetaryAmount add( MonetaryAmount value ) { return null; }
     public MonetaryAmount subtract( MonetaryAmount value ) { return null; }
    }
  2. Write a short Javadoc. Negative monetary amounts must not exist and must be blocked via an exception. 0 is allowed. The toString format is: no thousand separators, always two decimal places, decimal separator always the dot.

  3. Is there a method missing that should always be used for symmetry reasons?

  4. Create a new class com.tutego.money.MonetaryAmountTest for the test case. In what package do the class belong? Does the IDE support us?

  5. Implement appropriate test methods. What do we need to test?

  6. Implement all methods of the class MonetaryAmount.

  7. Are our data types chosen wisely? Do we need to correct a choice?