gpt4 book ai didi

java - 如何在 power mockito 中模拟生成的对象及其属性

转载 作者:行者123 更新时间:2023-12-02 10:15:40 26 4
gpt4 key购买 nike

我正在创建一个具有配置的适配器 Web 服务(代码如下)。我能够模拟'app'对象,但它的属性 'datasource' 为 null,即使我已经 mock 了它。如何模拟数据源及其连接属性?

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;
}

最佳答案

尝试更换这个:

private MyApp app = new MyApp();

这样:

@InjectMocks
private MyApp app;

关于java - 如何在 power mockito 中模拟生成的对象及其属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54705014/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com