Test Driven Development - As a Beginner
My Journey with Test-Driven Development
Many years ago, when I started working on a new project, my Architect & the head of the Project wanted us to follow Test Driven Development (TDD) approach. That was the first time I heard about this concept. As with any other developer even I was in the mindset that writing a test first is not going to work and is very time-consuming. But, I wanted to give it a try. I started by writing a test for a simple method that I needed to implement in my code.
Here's an example of the test that I started playing with TDD:
public void testAddition() {
Calculator calculator = new Calculator();
int result = calculator.add(2, 3);
assertEquals(5, result);
}
This test checks that the add method of the Calculator class correctly adds two numbers together. The assertEquals method checks that the result is equal to the expected value, which is 5 in this case. Next, I ran the test and of course, it failed because I hadn't written any code yet.
Step 1: Write a failing test
public class Calculator {
public int addition(int a, int b) {
return a + b;
}
}
@Test
public void testMultiplication() {
Calculator calculator = new Calculator();
int result = calculator.multiply(2, 3);
assertEquals(6, result);
}
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int multiply(int a, int b) {
return a * b;
}
}
I continued to write tests for each method that I needed to implement and followed the same process of writing the minimum amount of code necessary to make the test pass, refactoring the code, and running the test again.

Comments
Post a Comment