Search code examples
javaspringtestcasetest-coverage

Should I write different test case for different branch of same service?


  @Override
  public User editDescription(User user, String description) throws UserNotFoundException {
    user.setAboutMe(description);
    User returnedUser = userRepository.save(user);
    if (returnedUser == null) {
      throw new UserNotFoundException();
    }
    return returnedUser;
  }

I have this service implementation and the test case is:

    @Test
    public void shouldEditDescriptionOfTheUser() throws UserNotFoundException{
    databuilderService.createAll();
    User user = userService.findByEmail("abc@gmail.com");

    user.setAboutMe("It's a description about the user");
    userService.save(user);
    String aboutMe = user.getAboutMe();
    LOGGER.info(aboutMe);
    Assert.assertNotNull(aboutMe);
  }

is this test case covering all the branches ? Should I write another test case for checking the value of user object(null checking) which is a branch in service ?


Solution

  • is this test case covering all the branches ?

    No it does not.

    Obvious it does cover nothing, because it does not invoke the method under test at all!

    BTW: I do not know your repository, but it is likely that userRepository.save(user) always return the given user, so maybe the if (returnedUser == null) is nonesence, and it is more usefull to remove that if instead of writing an test for.

    Should I write another test You should start to make your first test a usefull test. This test is not a test at all. Because it does not even invoke the method under test!

    Replace the Logger with an assert first and invoke the method:

    @Test
    public void shouldEditDescriptionOfTheUser() throws UserNotFoundException{
       databuilderService.createAll(); //I would create just a single user instead
       User user = userService.findByEmail("abc@gmail.com");
    
       String newDesciption = "It's a description about the user";
       Assert.notEquals("precondition", newDesciption , user.getAboutMe);      
    
       xxx.editDescription(user, newDesciption); 
    
       Assert.assertEquals(newDesciption, user.getAboutMe());
    }
    

    Maybe also check that the user is really saved.

    You can also have an other test, that test that the user is created in the datebase when it was not loaded/or saved before.