Search code examples
javapowermockpowermockito

How to mock generated object and its attribute in power mockito


I am creating an adapter web service that has configuration (codes below). I am able to mock the 'app' object but its attribute 'datasource' is null even I have mocked it. How can I mock the data source and its connection attribute?

MyAdapter.java

public class MyAdapter {

 @Context
 private ConfigurationAPI configApi;

 @Context
 private AdaptersAPI adaptersAPI;

 public Connection getSQLConnection() throws SQLException {

    JavaAdapter app = adaptersAPI.getJaxRsApplication(JavaAdapter.class);
    return app.getDataSource().getConnection();
   }
}

MyAdapterTest.java

     @RunWith(PowerMockRunner.class);
     public class MyAdapterTest {

         @Mock
         DataSource dataSource;

         @Mock
         private ConfigurationAPI configApi;

         @Mock
         private AdaptersAPI adaptersAPI;

         @InjectMocks
         MyJavaAdapter myAdapter;

         private MyApp app = new MyApp();

         @Test
         public void getSQLConnectionTest() throws SQLException {

     PowerMockito.when(adaptersAPI.getJaxRsApplication(JavaAdapter.class).thenReturn(app);
     PowerMockito.when(app.getDataSource()).thenReturn(dataSource);
           }
        }

MyApp.java

 public class MyApp extends MFPJAXRSApplication{


    private DataSource dataSource = null;

    @Override
    protected void init() throws Exception {

        InitialContext ctx = new InitialContext();
        dataSource = (DataSource) ctx.lookup("customPath");
    }

    @Override
    protected void destroy() throws Exception {

    }

    @Override
    protected String getPackageToScan() {
        return getClass().getPackage().getName();
    }

    public DataSource getDataSource() {
        return dataSource;
    }

Solution

  • Try to reaplace this:

    private MyApp app = new MyApp();
    

    with this:

    @InjectMocks
    private MyApp app;