我想模拟一个 Datasource 和 InitialContext 以连接到容器外的数据库。这是我想使用模拟的逻辑:
Connection con = null;
Context context = new InitialContext();
DataSource datasource = (DataSource) context.lookup("jdbc/chu");
con = datasource.getConnection();
这就是我进行的方式
// create the Connection
connection = createMyConnection();//connection i construct manually
// Mock the Datasource
DataSource datasourceMock = EasyMock.createMock(DataSource.class);
EasyMock.expect(datasourceMock.getConnection())
.andReturn(connection).anyTimes();
// Mock the context
Context contextMock = EasyMock.createMock(InitialContext.class);
EasyMock.expect((DataSource)contextMock.lookup("jdbc/chu"))
.andReturn(datasourceMock)
.anyTimes();
PowerMock.expectNew(InitialContext.class).andReturn((InitialContext)contextMock);
// run the mock
PowerMock.replayAll();
问题:模拟不适用于 DataSource 它始终为空,但是 InitialContext 的模拟正在工作。