0

I have a class, which I want to unit test using mockito:

public class ServiceImpl {

    @Autowired
    private TestDao testDao;

    @Transactional
    public void setData(Long id) {
        TestClass testClass = testDao.findOne(id);
        if (testClass != null) {
            testClass.setStatus(true);
        }
    }
}

I need to test this class. So I have created the Test class as below:

@RunWith(MockitoJUnitRunner.class)
public class ServiceImplTest{
    @Mock
    private TestDao testDao;

    @InjectMocks
    private ServiceImpl service;

    @Test
    public void setData_success() {
        TestClass testClass = new TestClass();
        when(testDao.findOne(1L)).thenReturn(testClass);
        service.setData(1L);
        assertTrue(testClass.getStatus());
    }
}

The above scenario is when the testClass object is present. Similarly i want to test, the scenario when the testClass object is null. Something like:

 @Test
 public void setData_testClass_null() {
    TestClass testClass = null;
    when(testDao.findOne(1L)).thenReturn(testClass);
    service.setData(1L);
    //how to I verify here that testClass.setStatus(true) is never called????
   //or should I just ignore the test case?
  }
Mendon Ashwini
  • 594
  • 7
  • 28
  • Wouldn't you get a NullPointerException if it were called? Doesn't the absence of this exception indicate that it wasn't called? – Tom Sep 12 '19 at 09:24
  • Yes... But how do I mention that in my test case? – Mendon Ashwini Sep 12 '19 at 09:27
  • It's not a very good test, especially when you're white-box testing it. You're basically checking whether the null check exists in code. – Kayaman Sep 12 '19 at 09:38
  • @kayaman the sonar lint gives warning saying that the condition is not covered in test case. – Mendon Ashwini Sep 12 '19 at 09:42
  • @MendonAshwini well if you're trying to get 100% test coverage. But as a test it's pretty useless. It would fail if someone decided to remove the null check from that code, but it's not like you can accidentally do it. – Kayaman Sep 12 '19 at 09:47
  • Sonar might do that, but the question could be something else: should `setData` really silently do _nothing_ when it can't find the entity in the database? Isn't an `EntityNotFoundException` suitable here? That can also be explicitly tested. – Tom Sep 12 '19 at 09:48
  • TestClass null check is just validation and did not want to throw an exception. – Mendon Ashwini Sep 12 '19 at 10:17
  • The sonar would be complaining about branch coverage. Current code will have 100% code coverage but branch coevrage = 50%. Like @Kayaman said, this not a good test and you will get NPE in first line itself. If you still want to continue then you can add try catch NPE. Then add test for expecting NPE. Ex - assertThows(Junit5) NPE. OR in Junit 4 @Test(NullPointerException) – Dinesh Arora Apr 20 '20 at 15:39

0 Answers0