A Tribute to Writers of Unorganized Test Code
Aditya Roshan
Engineering Leader | 17+ Years Driving Scalable Software Solutions | Innovating with Generative AI & Advanced Technologies
When you inquire with a Developer about how thoroughly they’ve tested their code
The issue here is that the code for Unit Tests, Functional Tests, and Regression Tests
As the code becomes bigger over time and when we add new features, they can sometimes cause existing things to stop working correctly. But usually, people don’t consider spending time to write tests for these changes.
Sometimes, even if we write test code just to meet the requirements, it might not follow the good coding rules
For those who write messy tests, there’s a rule called “FIRST” that should be kept in mind when creating test code:
Fast: Make sure your tests complete quickly. I’ve observed situations where test suites take hours to finish, which can sometimes become quite frustrating.
Here’s a simple example where you’re testing a function that adds two numbers:
@Test
public void testAddition() {
int result = Calculator.add(3, 5);
assertEquals(8, result);
}
Isolated/Independent: Ensure that every test is self-contained and doesn’t depend on or influence the results of other tests. This approach allows you to run different tests separately and autonomously.
Here’s an example testing a class that simulates a stack:
领英推荐
@Test
public void testPush() {
Stack stack = new Stack();
stack.push(42);
assertEquals(1, stack.size());
}
@Test
public void testPop() {
Stack stack = new Stack();
stack.push(42);
int poppedValue = stack.pop();
assertEquals(42, poppedValue);
assertEquals(0, stack.size());
}
Repeatable: Make certain that tests always generate consistent outcomes, meaning they yield the same results whether run once or a hundred times. The output should remain unchanged.
Here’s an example testing a sorting method:
@Test
public void testSort() {
int[] unsorted = {3, 1, 4, 1, 5};
int[] sorted = {1, 1, 3, 4, 5};
Arrays.sort(unsorted);
assertArrayEquals(sorted, unsorted);
}
Self-validating: Tests should possess distinct criteria for passing or failing. This entails including both positive and negative scenarios within the test code.
Here’s an example testing a method to check if a number is prime:
@Test
public void testIsPrime() {
assertTrue(MathUtil.isPrime(17));
assertFalse(MathUtil.isPrime(6));
}
Timely: Start writing tests early
Here’s an example testing a method that calculates the Fibonacci sequence:
@Test
public void testFibonacci() {
assertEquals(0, MathUtil.fibonacci(0));
assertEquals(1, MathUtil.fibonacci(1));
assertEquals(55, MathUtil.fibonacci(10));
}
Happy coding?:)