Deterministic tests always give the same result when run with the same input. This helps us trust our tests and find real problems.
0
0
Deterministic tests in JUnit
Introduction
When testing a function that adds two numbers and should always return the same sum.
When checking if a method returns a fixed value for a given input.
When verifying that a sorting algorithm always sorts the list the same way.
When running tests that should not depend on time or random values.
When you want your tests to be reliable and repeatable every time.
Syntax
JUnit
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class MyTests { @Test void testMethod() { // Arrange int input = 5; int expectedValue = 10; // Act int result = input * 2; // e.g., someMethod(input) // Assert assertEquals(expectedValue, result); } }
Use @Test annotation to mark a test method.
Assertions like assertEquals check if the output matches the expected value.
Examples
This test checks that adding 2 and 3 always equals 5. It is deterministic because the result never changes.
JUnit
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class CalculatorTest { @Test void addTwoNumbers() { int sum = 2 + 3; assertEquals(5, sum); } }
This test verifies that converting "hello" to uppercase always returns "HELLO".
JUnit
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class StringTest { @Test void testToUpper() { String result = "hello".toUpperCase(); assertEquals("HELLO", result); } }
Sample Program
This test checks that multiplying 4 by 2 always returns 8. The test is deterministic because the method multiplyByTwo always returns the same output for the same input.
JUnit
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class DeterministicTestExample { int multiplyByTwo(int number) { return number * 2; } @Test void testMultiplyByTwo() { int input = 4; int expected = 8; int actual = multiplyByTwo(input); assertEquals(expected, actual); } }
OutputSuccess
Important Notes
Deterministic tests do not rely on random numbers or current time.
Keep tests simple and predictable to avoid flaky results.
Use clear assertions to compare expected and actual results.
Summary
Deterministic tests always produce the same result for the same input.
They help make tests reliable and easy to trust.
Use assertions to check expected outcomes clearly.