简体   繁体   中英

supressing NullPointerException in Mockito?

DAOClass.makeDBConnection() method returns datasource configured (using lookup) in Application Server (Jboss). Need to implement junit test case for this scenario.

Using Mockito, tested the DAO method as follows. As it's not able to find the datasource(as expected), it's returning NullPointerException. How to handle NullPointerException and return the connection which i am creating in below code? OR is there any other better unit test framework which handles this scenario ?

    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
    Connection conn = DriverManager.getConnection("jdbc:sqlserver://DB:1433;DatabaseName=databasename", "userid", "password");

    when(DAOClass.makeDBConnection()).thenReturn(conn);

Mockito can't mock static method calls the way you have it; it effectively works by dynamically overriding all methods via a generated subclass (proxy).

You will need to write a wrapper class around static methods that you want to mock, otherwise refactor the code to avoid the static call, or use a tool such as PowerMock to rewrite your system's bytecode at runtime.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM