0
I want to execute the catch block of the below code.

public String getResult() {
    try {
        return InetAddress.getLocalHost().getHostName();
    } catch (Exception e) {
        throw new Exception(e);
    }
}

i write the test case as follows,

@Test
public void getResultTest() throws Exception{
    doThrow(Exception.class).when(mockInetAddress).getLocalHost();
    mockTestClassObj.getResult();
    //code for verify exception
}

This executes fine instead throws exception. Can't i throw exception in this scenario?

Progman
  • 14,690
  • 4
  • 32
  • 46
Sweety
  • 127
  • 7
  • Welcome to Stack Overflow. Please take the [tour] to learn how Stack Overflow works and read [ask] on how to improve the quality of your question. Then [edit] your question to include the full source code you have as a [mcve], which can be compiled and tested by others. – Progman Feb 23 '21 at 16:24
  • Does this answer your question? [Mocking static methods with Mockito](https://stackoverflow.com/questions/21105403/mocking-static-methods-with-mockito) – polypiel Feb 23 '21 at 19:13

1 Answers1

0

getLocalHost() is a static method so you cannot mock it easily

Take a look to Mocking static methods with Mockito

polypiel
  • 2,171
  • 1
  • 18
  • 27