0

How to mock the below method using Mockito or PowerMock without providing the class in PrepareForTest

class Test{
    public static void test(){
        getConnection();
    }

    public static Connection getConnection() throws NamingException, SQLException {
        InitialContext localInitialContext = new InitialContext();
        DataSource localDataSource = (DataSource) localInitialContext.lookup(JNDINames.DATASOURCE);
        Connection localConnection = localDataSource.getConnection();
        return localConnection;
    }
}
vinS
  • 1,417
  • 5
  • 24
  • 37
user3428736
  • 864
  • 2
  • 13
  • 33
  • In this question, is `Test` the class you are testing or a dependency of the class you are testing? It's a bit unclear what you mean by 'without providing the class' - do you mean without mocking the class? If so, then the answer is that you can't mock a method without mocking the object it is a member of. – sprinter Dec 27 '19 at 11:12
  • If you use PowerMockito you will add the class to PrepareForTest with class name and it will affect the coverage and I dont want to use that way of implementation.Is there any other way to mock this class – user3428736 Dec 27 '19 at 11:45
  • what do you think about _offline-instrumentation_? – Renato Dec 28 '19 at 23:04
  • But It is not helping in jacoco coverage. – user3428736 Jan 02 '20 at 08:18

1 Answers1

0

Tried this below link and it helped to resolve the issue, Thanks

How to mock InitialContext constructor in unit testing

user3428736
  • 864
  • 2
  • 13
  • 33