- Invade the Code 👽
- Posts
- 🌟 Day 11 of #100DaysOfCode: TDD Adventures! 🌟
🌟 Day 11 of #100DaysOfCode: TDD Adventures! 🌟
Hey Invaders! 👽
#100daysofcode day 11, I continued working on my JUnit course and finished section 7: Test Driven Development (TDD). Today, I practiced creating a test createUser
method and followed the TDD cycle: red, green, refactor, repeat. This process involves writing a failing test first, then implementing the production code to make the test pass, and finally refactoring the code to improve its structure without changing its behavior.
Feeling more confident with TDD and excited to apply these principles in real projects! Here's a snippet of my createUser
test methods
public class UserServiceTest {
UserService userService;
String firstName;
String lastName;
String email;
String password;
String repeatPassword;
//Arrange for each test instance
@BeforeEach
void init() {
userService = new UserServiceImpl();
firstName = "ari";
lastName = "vanegas";
email = "[email protected]";
password = "1234567";
repeatPassword = "1234567";
}
@DisplayName("User object created")
@Test
void testCreateUser_whenUserDetailsProvided_ReturnUserObject() {
//Act
User user = userService.createUser(firstName, lastName, email, password, repeatPassword);
//Assert
assertNotNull(user, "The createUser() should not have returned null");
assertEquals(firstName, user.getFirstName(), "users first name does not match");
assertEquals(lastName, user.getLastName(), "users last name does not match");
assertEquals(email, user.getEmail(), "users email does not match");
assertNotNull(user.getId(), "user id is missing");
}
@DisplayName("Empty first name causes correct exception")
@Test
void testCreateUser_whenFirstNameIsEmpty_throwsIllegalArgumentException() {
firstName = "";
//Act & Assert
IllegalArgumentException thrown = assertThrows(IllegalArgumentException.class, () -> {
userService.createUser(firstName, lastName, email, password, repeatPassword);
}, "Empty first name should have cause and Illegal Argument Exception");
//Assert
assertEquals("User's first name is empty", thrown.getMessage(),
"Exception error message is not correct");
}
Follow my GitHub to check out the rest of the implementations in the code as per the tests: avrubio/JUnitUdemyCourse.
Keep pushing forward and happy coding! 💪
Let's conquer this journey together! 🚀
Reply