Search code examples
javaunit-testingjdbcmockitopowermockito

JDBC connection not working with PowerMockito


I am trying to use PowerMockito to mock by DBUtil. Unlike typical testcase, I don't want to mock the db calls completely. Whenever Dbutil.getConnection() is called. I want to return the connection object to my local Database.

The simple jdbc connection code below is not working when i call from @BeforeClass method. But it works when I call from the java class.

public static Connection getConnection() throws Exception {
    System.out.println("-------- Connecting to  " + Constants.CONNECTION_STR + "  ------");

    try {
        Class.forName(Constants.ORACLE_DRIVER_NAME);
    } 
    catch (ClassNotFoundException e) {          
        throw new Exception("JDBC Driver not found... " + e);           
    }
    catch (Exception e) {
        // TODO: handle exception
        System.out.println("getConnection :: exp :: "+ e);
    }

    System.out.println("Oracle JDBC Driver Registered Sucessfully!");

    Connection connection = null;

    try {
        connection = DriverManager.getConnection(Constants.CONNECTION_STR, Constants.USERNAME, Constants.PASSWORD);
    } 
    catch (SQLException e) {
        throw new Exception("Connection Failed!",e);                        
    }   

    if (connection != null) {
        System.out.println("Connected to Database Sucessfully, take control your database now!");
        return connection;
    } 

    System.out.println("Failed to make connection!");
    return null;
}

My Testclass

@RunWith (PowerMockRunner.class)
@PrepareForTest(DbUtil.class)
public class MyUtilTest {

@Mock
private DbUtil dbUtil;

@InjectMocks
private MyUtil myUtil;

private static Connection myDBConn;


@BeforeClass
public static void beforeClass() throws Exception {           
    myDBConn = OracleJDBCConnetion.getConnection(); // This always throws invalid username/password exception.
}

@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
}

@Test
public void testIsAdminUser() throws Throwable{


    PowerMockito.mockStatic(DbUtil.class);          
    PowerMockito.when(DbUtil.getConnection()).thenReturn(myDBConn);     

    String accId= "TH123" ;
    boolean  isAdmin = MyUtil.isAdminUser(cloudAccGuid);        
    System.out.println("isAdmin  : " + isAdmin);

    //then
    PowerMockito.verifyStatic(Mockito.times(1));
    DbUtil.getConnection();
    assertTrue(isAdmin);


    //Finally I am closing my connection.
    if(myDBConn!=null &&  !myDBConn.isClosed())
        OracleJDBCConnetion.closeConnection(myDBConn);

}

}

The beforeClass method always throws below expection.

Connection Failed! java.sql.SQLException: ORA-01017: invalid username/password; logon denied

But the same code works, when i try from normal Java class.

Can anyone help in understanding whats wrong here?

I am using ojdbc6.jar and powermokito-1.5.6 and my Oracle database version is 11.2.0.4.0

Thanks.

Edit : I found that @PrepareForTest annotation is causing the error. without the annotation connection is successful but mock does not work. can anyone help me in understanding what is happening? I am very new to these mocking stuff.


Solution

  • The problem with @PrepareForTest annotation is, it recursively creates stubs for all dependent classes. Since DBUtil class uses java.sql.Connection class , a stub is created for Connection class also.

    So, When i try to create connection, it refers to stub class and throws expection.

    Add @PowerMockIgnore annotation to the class,to avoid it. @PowerMockIgnore annotation tells the powermock not to create for the classes that falls under the given package.

    @RunWith (PowerMockRunner.class)
    @PrepareForTest({DbUtil.class})
    @PowerMockIgnore({"java.sql.*"})
    public class MyUtilTest {
      ... 
    }
    

    This worked for me.