Issue
I am currently been assigned to creating Junit tests for a project. I created some test, however after reading up on some best practices I discovered that Junit tests should not affect real data as it can comprise integrity of the data.
One test for example below tests the Editing of an existing user's data in the repository:
@Test
void EditUserTest()
{
UserController userController = new UserController();
List<User> userList = (List<User>) userController.getCurrentUserlist();
RoleController roleController = new RoleController();
List<Role> roleList = (List<Role>) roleController.GetCurrentRolelist();
User selectedUser = userList.get(0);
selectedUser.setLoginName("EditedLoginName");
selectedUser.setFirstName("EditedFirstName");
selectedUser.setLastName("EditedLastName");
selectedUser.setEmployeeID(555555555);
selectedUser.setRole(roleList.get(6));
selectedUser.setAutoLogoutPeriod(6);
selectedUser.setEksSerial("45f869");
selectedUser.setEksLevel(9);
User NonExistent = new User();
assertTrue(userController.EditUser(selectedUser), "Testing edit to User in repository");
assertFalse(userController.EditUser(NonExistent), "Testing edit to Non-Existent User in repository");
User editedUser = userController.GetUser(selectedUser.getID());
assertEquals("EditedLoginName", editedUser.getLoginName(), "Testing edit to User Login name");
assertEquals("EditedFirstName", editedUser.getFirstName(), "Testing edit to User First name");
assertEquals("EditedLastName", editedUser.getLastName(), "Testing edit to User Last name");
assertEquals(55555555, editedUser.getEmployeeID(), "Testing edit to User Employee ID");
assertEquals(roleList.get(6), editedUser.getRole(), "Testing edit to User Role");
assertEquals("45f869", editedUser.getEksSerial(), "Testing edit to User Eks Serial");
assertEquals(9, editedUser.getEksLevel(), "Testing edit to User Eks Level");
}
As you can see I retrieve a list of the current users within the repository and just take the first one. After changing its values I then make the actual edit to the repository using the controller and later retrieve the same user from the repository to compare and see if an edit was actually made. Now how would I test this same thing without actually affecting the real data within the repository?
Solution
Unit tests are not supposed to access real data. You need to mock any such data so that the real data is not affected.
The purpose of unit tests is to test the functionality, it isn't dependent on the real data.
You can look into Mockito for mocking objects that exhibit the behavior of actual objects.
This link might be helpful: Official docs
Answered By - Usman Rafi