我正在创建一个具有配置的适配器 Web 服务(下面的代码)。我可以模拟“app” 对象,但它的属性“datasource”是空的,即使我已经模拟了它。如何模拟数据源及其连接属性?
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;
}
元芳怎么了
鸿蒙传说
相关分类