QA AND TEST AUTOMATION · PART 2 · PROGRAMMING FOR TESTERS · JAVA · 25 OF 112

Maven and JUnit 5 for Testers: Your First Test Project

How a Java test project is built: the Maven folder layout, pom.xml with pinned JUnit and Surefire versions, dependencies and scopes, the build life cycle (mvn test), then JUnit 5 tests with assertions, assertAll, assertThrows, lifecycle hooks, parameterized boundary tests and reading the Surefire report. Written for the ShopRung pricing rules, as in lab 4.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 67
  63. 68
  64. 69
  65. 70
  66. 71
  67. 72
  68. 73
  69. 74
  70. 75
  71. 76
  72. 77
  73. 78
  74. 79
  75. 80
  76. 81
  77. 82
  78. 83
  79. 84
  80. 85
  81. 86
  82. 87
  83. 88
  84. 89
  85. 90
  86. 91
  87. 92
  88. 93
  89. 94
  90. 95
  91. 96
  92. 97
  93. 98
  94. 99
  95. 100
  96. 101
  97. 102
  98. 103
  99. 104
  100. 105
  101. 106
  102. 107
  103. 108
  104. 109
  105. 110
  106. 111
  107. 112
1 / 14

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Standard layout
  • pom with pinned versions
  • mvn test and Surefire
  • @Test, assertAll, assertThrows
  • parameterized boundaries

Notes

The layout

Maven expects a standard layout, so every Java project looks the same. The pom dot xml file at the top describes the project. Code goes under source, main, java. Tests go under source, test, java, in the same package as the code they test. Maven writes everything it builds into a folder called target, which you never commit to Git. Learn this layout once and you can open any Java test repository and find your way around.

Project layout
shoprung-tests/
  pom.xml
  src/main/java/
    dev/algorung/shop/
      Coupon.java
  src/test/java/
    dev/algorung/shop/
      PricingTest.java
  target/      (build output,
               never commit)

pom.xml

The pom names the project with a group id and an artifact id, sets the Java version to twenty one, and lists dependencies. Here there is one: JUnit Jupiter, version five point eleven point four, with test scope, which means it is only used by test code. When you build, Maven downloads it from Maven Central into a cache on your computer. Always pin exact versions, so the suite behaves the same on every machine and in CI.

pom.xml (the key parts)
<groupId>dev.algorung</groupId>
<artifactId>shoprung-tests
  </artifactId>
<maven.compiler.release>21
<dependency>
  <groupId>org.junit.jupiter
  <artifactId>junit-jupiter
  <version>5.11.4</version>
  <scope>test</scope>
</dependency>

Plugins

Maven itself does little. Plugins do the work. The compiler plugin compiles your code. The Surefire plugin runs the tests: by default it finds classes whose names end in Test and runs them with JUnit five. Pin plugin versions too. Old Surefire versions do not see JUnit five tests at all, which leads to a confusing build success with zero tests run. If you ever see tests run zero, check this first.

Build plugins
<plugin>
  maven-compiler-plugin
  <version>3.13.0</version>
</plugin>
<plugin>
  maven-surefire-plugin
  <version>3.5.2</version>
</plugin>

Surefire finds *Test.java
and runs them with JUnit 5

Life cycle

Maven has a build life cycle. Running m v n test runs every phase up to test: validate, compile the code, compile the tests, then run them. Add dash D test equals a class name to run one class, or a hash and a method name to run one test. m v n clean test deletes the target folder first, for a fresh build. At the end, Surefire prints a summary line: tests run, failures, errors and skipped.

Commands
mvn test
  validate → compile →
  test-compile → test
mvn test -Dtest=PricingTest
mvn test -Dtest=PricingTest#
  cartTotals
mvn clean test   (fresh build)
mvn -q test      (quiet)

[INFO] Tests run: 19,
  Failures: 0, Errors: 0

A JUnit test

A JUnit test is a method marked with the at test annotation. Good tests follow three steps: arrange the data, act by calling the code, and assert the result. Four notebooks make five thousand cents, save ten's discount on that is five hundred, and assert equals checks it. Note the argument order: expected first, actual second. Swap them and the failure message tells the wrong story. Give tests names that read like the requirement.

PricingTest.java
class PricingTest {
  @Test
  void save10AtExactlyFifty() {
    long sub = 4 * 1250;  // arrange
    long d = Coupon.SAVE10
        .discount(sub);    // act
    assertEquals(500, d);  // assert
  }
}
// assertEquals(expected, actual)

Assertions

Pick the assertion that gives the clearest failure. Assert equals for exact values, assert true and assert null for conditions. Assert all groups several checks and reports every failure, not just the first, which is ideal for a cart's subtotal, shipping and total. Assert throws checks that code refuses bad input with the right exception, like a quantity of eleven, and returns the exception so you can check its message too.

Useful assertions
assertEquals(500, d);
assertTrue(total > 0);
assertNull(problem);
assertAll("totals",
  () -> assertEquals(5000, sub),
  () -> assertEquals(499, ship),
  () -> assertEquals(4999, tot));
var e = assertThrows(
  IllegalArgumentException.class,
  () -> Cart.quantity(11));

Parameterized

Parameterized tests run one test method with many rows of data, which is exactly how boundary values should be automated. CSV source gives each row: forty nine ninety nine gets no discount, fifty dollars gets five, fifty oh four gets five, and fifty oh five gets five dollars and one cent, the rounding edge. Each row appears as its own test in the report, named with the pattern you give, so a failure says exactly which boundary broke.

@ParameterizedTest
@ParameterizedTest(name =
  "{0} cents -> discount {1}")
@CsvSource({
  "4999, 0",
  "5000, 500",
  "5004, 500",
  "5005, 501"
})
void save10(long sub, long d) {
  assertEquals(d, SAVE10
    .discount(sub)); }

Lifecycle hooks

JUnit has hooks that run around tests. Before each and after each run around every test; before all and after all run once per class and must be static. A common use: before each test, reset ShopRung's data, so every test starts clean and tests never depend on each other. Display name gives a readable name, and disabled skips a test. Always say why it is disabled, with a bug id, or it will stay disabled forever.

JUnit 5 hooks
@BeforeAll  static, once
@BeforeEach before every test
@AfterEach  after every test
@AfterAll   static, once

@BeforeEach void reset() {
  api.post("/api/test/reset");
}
@DisplayName("SAVE10 rules")
@Disabled("bug B-7")  // say why

Reading failures

When a test fails, read the failure from the top. It names the test and line, the parameter row that failed, and expected versus actual: expected five hundred but was zero. That is the off by one bug at fifty dollars. The build ends in build failure, which also fails the pipeline. A failure means an assertion was wrong; an error means the test itself crashed with an exception. Detailed reports land in target, surefire reports.

A failing run
[ERROR] Failures:
[ERROR] PricingTest.save10:52
  4999 cents -> discount 0
  5000 cents -> discount 500
  expected: <500> but was: <0>

[ERROR] Tests run: 19,
  Failures: 1, Errors: 0
[INFO] BUILD FAILURE
reports: target/surefire-reports

Good tests

Rules that keep a suite fast and trustworthy. Test one behaviour per test, with a name that reads like the rule. Never let one test depend on another having run first. No thread sleep. Exact expected values. And see each test fail at least once: break the code on purpose, run it, then put it back. A test you have never seen fail may not be testing anything. In lab four you do exactly that with the coupon boundary.

Rules of thumb
  • one behaviour per test
  • names that read like rules
  • no test depends on another
  • no Thread.sleep
  • exact expected values
  • see each test FAIL once: break the code on purpose
  • fast unit tests, many; slow UI tests, few
  • pin every version

Common mistakes

Mistakes in Java test projects. Test classes whose names do not end in test, so Surefire never runs them. An old Surefire that runs zero tests. Assert equals with actual and expected swapped. JUnit four and five imports mixed in one class. Tests placed under source main instead of source test. Committing the target folder. And unpinned versions that change under your feet.

Avoid these
  • test classes not ending in Test → never run
  • old Surefire → 0 tests run
  • assertEquals(actual, expected)
  • JUnit 4 and 5 imports mixed
  • tests in src/main/java
  • committing target/
  • unpinned versions

Say it like this

In the interview: my project is a Maven project with a pom that pins JUnit five and Surefire, and tests under source test java. m v n test runs the suite locally and in CI. Tests follow arrange, act, assert, are independent, use parameterized tests for boundaries and assert all for related checks, and reset data in before each. If asked about TestNG, say it is common in Selenium suites and comes later in Part seven.

In the interview
  • "A Maven project: pom.xml with pinned JUnit 5 and Surefire, tests under src/test/java.
  • mvn test runs locally and in CI. Tests are arrange-act- assert, independent, with parameterized tests for boundaries, assertAll for related checks, and setup in @BeforeEach."

Interview questions

Q1What is Maven and why use it?

A build tool that standardises the project layout, downloads dependencies from repositories, and runs the build life cycle (compile, test, package) with one command, the same locally and in CI.

Q2What is the difference between a dependency scope of compile and test?

compile dependencies are available to main and test code and shipped with the app; test dependencies (like JUnit) are only on the test classpath.

Q3What does the Surefire plugin do?

It runs unit tests during the test phase, finding classes such as *Test.java, and writes reports to target/surefire-reports.

Q4What is the difference between a failure and an error in JUnit?

A failure is an assertion that did not hold; an error is an unexpected exception thrown by the test or the code under test.

Q5What are the JUnit 5 lifecycle annotations?

@BeforeAll and @AfterAll (once per class, static), @BeforeEach and @AfterEach (around every test).

Q6When would you use assertAll?

When several related checks belong together, such as subtotal, shipping and total, so the report shows every failing check, not only the first.

Q7How do you write a data-driven test in JUnit 5?

With @ParameterizedTest and a source such as @CsvSource, @ValueSource or @MethodSource; each row runs as a separate test case.

Q8How do you run a single test with Maven?

mvn test -Dtest=ClassName or mvn test -Dtest=ClassName#methodName.