我正在创建一个具有配置的适配器 Web 服务(下面的代码)。我可以模拟“app” 对象,但它的属性“datasource”是空的,即使我已经模拟了它。如何模拟数据源及其连接属性?MyAdapter.javapublic 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; }
2 回答
鸿蒙传说
TA贡献1865条经验 获得超7个赞
您不能在未模拟的对象上设置模拟实例(您可以通过调用 setter 方法来设置它们)。而是尝试模拟MyApp
@Mock
private MyApp app
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
然后你可以使用下面的语句来模拟DataSource
PowerMockito.when(app.getDataSource()).thenReturn(dataSource);
添加回答
举报
0/150
提交
取消