QA AND TEST AUTOMATION · PART 3 · AUTOMATION FUNDAMENTALS · UNIT · 31 OF 112

Unit Testing With JUnit 5 and pytest, Side by Side

What a unit test is and is not, what makes one good (fast, isolated, repeatable, self-checking, one reason to fail), and how the same tests look in JUnit 5 and pytest: assertions, expected exceptions, parameterized boundaries, fixtures and setup, and reading failures. Worked on the ShopRung discount rule, with the real pytest output when the rounding bug is planted.

  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 / 12

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

Key takeaways

  • One unit, alone
  • FIRST
  • parameterized boundaries
  • fixtures
  • test behaviour
  • see it fail

Notes

What a unit is

A unit test checks one small piece of logic, a function, a method, or a small class, on its own. No database, no network, no browser, no real clock and no randomness, so it runs in milliseconds and gives the same answer every time. A useful test of your understanding: if a test needs ShopRung to be running, it is not a unit test. It is an integration or API test, which the next parts cover.

A unit test
  • checks one unit: a function, a method, a small class
  • alone: no database, no network, no browser, no clock, no random
  • runs in milliseconds
  • not a unit test: anything
  • that needs ShopRung running

Good unit tests

Good unit tests follow FIRST. Fast: milliseconds each. Isolated: no shared state, so they pass in any order. Repeatable: the same result on every run and every machine. Self checking: they say pass or fail, nobody reads logs to decide. And timely: written with the code, not months later. Add one more rule: each test should have one reason to fail, so a red test tells you exactly which behaviour broke.

FIRST
  • Fast: milliseconds
  • Isolated: no shared state, any order works
  • Repeatable: same result every run, every machine
  • Self-checking: pass or fail, no reading logs
  • Timely: written with the code
  • + one reason to fail per test

JUnit 5

Here is ShopRung's save ten rule tested in JUnit five. A parameterized test feeds four rows: forty nine ninety nine gets no discount, fifty dollars gets five hundred cents, fifty oh four still five hundred, and fifty oh five gets five hundred and one, the rounding edge. A second test checks that a negative subtotal is refused with an illegal argument exception. You built this kind of project in the Maven episode and lab four.

DiscountTest.java
@ParameterizedTest
@CsvSource({"4999, 0",
  "5000, 500", "5004, 500",
  "5005, 501"})
void save10(long sub, long exp) {
  assertEquals(exp,
      Pricing.discount(sub));
}
@Test void negativeRefused() {
  assertThrows(IllegalArgument
    Exception.class, () -> ...); }

pytest

The same tests in pytest. A test is any function whose name starts with test, in a file whose name starts with test. Assertions are the plain Python assert statement, and pytest rewrites them to show both values when they fail. Parametrize gives the same four rows. pytest dash q runs everything quietly. Run against the real discount function, the four rows plus a type check report five passed in about ten milliseconds.

test_pricing.py
import pytest
from pricing import discount

@pytest.mark.parametrize(
  "subtotal, expected", [
  (4999, 0), (5000, 500),
  (5004, 500), (5005, 501)])
def test_save10(subtotal, expected):
    assert discount(subtotal) == \
        expected
# pytest -q → 5 passed

Side by side

Side by side, the two frameworks are the same ideas with different spelling. At test becomes a function named test something. Assert equals becomes a plain assert. Assert throws becomes pytest dot raises used in a with block. Parameterized tests become the parametrize mark. Before each becomes a fixture. Disabled becomes skip with a reason. And m v n test becomes pytest dash q. Learn one well, and the other takes an afternoon.

JUnit 5 ↔ pytest
@Test            def test_x():
assertEquals(a,b) assert b == a
assertThrows      pytest.raises
@ParameterizedTest
                  @pytest.mark
                    .parametrize
@BeforeEach       @pytest.fixture
@Disabled("why")  @pytest.mark
                    .skip(reason=)
mvn test          pytest -q

A real failure

Plant ShopRung's rounding bug: drop the plus fifty, so the discount always rounds down. Run pytest. One row fails: assert five hundred equals five hundred and one, where five hundred is discount of fifty oh five. The test id in square brackets names the exact row. Four rows still pass, including fifty dollars itself. This is why the rounding edge row exists: without it, the bug ships. Always see a test fail like this once.

Rounding down by mistake
# bug: (subtotal * 10) // 100
>  assert discount(subtotal) ==
       expected
E  assert 500 == 501
E   +  where 500 =
        discount(5005)
FAILED test_pricing.py::
  test_save10[5005-501]
1 failed, 4 passed

Fixtures

Tests often need the same setup, like a fresh empty cart. JUnit uses before each, which creates the cart before every test. pytest uses fixtures: a function marked as a fixture returns the cart, and any test that names it as a parameter receives a fresh one. Fixtures can also clean up after the test with yield. The key is fresh: each test gets its own object, so no test leaves a mess for the next.

Setup, both ways
// JUnit
@BeforeEach void newCart() {
  cart = new Cart(); }

# pytest
@pytest.fixture
def cart():
    return Cart()
def test_add(cart):
    cart.add("MG-201", 2)
    assert cart.count() == 2

What to test

What should unit tests cover? Each rule's partitions and boundaries, the error paths with their exceptions and messages, and edge values like zero, empty, the maximum and rounding halves. What should they skip? Private helper methods, simple getters and the framework's own code. Test behaviour through the public interface, what the code does, not how it does it, so tests survive refactoring instead of breaking every time the code is tidied.

What to cover
  • each rule's partitions and boundaries
  • error paths: bad input, exceptions and messages
  • edge values: 0, empty, max, rounding halves
  • not: private helpers, getters, framework code
  • test what, not how

Common mistakes

Unit tests that look busy but catch little. Tests with no assertion at all. Asserting whatever the code currently returns, instead of what the requirement says. One test checking ten behaviours. Tests that only pass in a certain order. Using the real clock or random values. Testing private methods directly. And copying the production formula into the test to compute the expected value, so both share the same bug. Write expected values by hand.

Avoid these
  • tests with no assertion
  • asserting what the code does, not what it should
  • one test, ten behaviours
  • tests that depend on order
  • real clock or random values
  • testing private methods
  • copying the production formula into the test

Say it like this

In the interview: a good unit test is fast, isolated, repeatable and self checking, with one reason to fail. It tests behaviour through the public interface with hand written expected values, covers boundaries and error paths, and I make sure it actually fails when the code is wrong. Then add that the framework matters less than the habits: JUnit five or pytest, the ideas are the same.

In the interview
  • "Fast, isolated, repeatable, self-checking, with one reason to fail. It tests
  • behaviour through the public
  • API with hand-written expected
  • values, covers boundaries and error paths, and I make sure
  • it fails when the code is wrong. JUnit 5 or pytest, the ideas are the same."

Interview questions

Q1What is a unit test?

An automated test of one small piece of logic (a function, method or class) in isolation from databases, networks, browsers, clocks and randomness, running in milliseconds.

Q2What does FIRST stand for?

Fast, Isolated (independent), Repeatable, Self-checking (self-validating) and Timely.

Q3How do you write a parameterized test in pytest?

With @pytest.mark.parametrize("a, expected", [(1, 2), ...]) on a test function that takes those parameters; each tuple runs as its own test.

Q4How do you test that a function raises an exception in pytest and JUnit?

pytest: with pytest.raises(ValueError): f(). JUnit 5: assertThrows(IllegalArgumentException.class, () -> f()), which also returns the exception to check its message.

Q5What is a pytest fixture?

A function marked @pytest.fixture that provides setup (and optional teardown with yield) to any test that names it as a parameter.

Q6Should you test private methods?

Generally no. Test behaviour through the public interface; private methods are covered indirectly, and tests stay valid when internals are refactored.

Q7Why not compute expected values with the same formula as the code?

The test would share the code's bug and always pass. Expected values should come from the requirement, worked out by hand.

Q8What is the difference between a unit and an integration test?

A unit test checks one piece in isolation; an integration test checks several pieces working together, such as an API with its database.