且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Java Web应用程序中使用数据源测试DAO?

更新时间:2023-09-17 12:12:28

AbstractRepository 中的代码很难测试。原因是智能构造函数,它知道他从哪里获取数据源。但是您仍然有很多选择。您可以更改代码(我的选择),以便构造函数接收 DataSource 作为参数,例如

The code you have in AbstractRepository is pretty hard to test. The reason is the "smart constructor", that knows where he gets the datasource from. But you still have a number of options. You can either change your code (my choice) so that the constructor receives DataSource as a parameter, like

public AbstractRepository(DataSource dataSource){
  this.ds = dataSource;
}

因此您将能够使用一些测试数据源在测试环境中初始化存储库(一个模拟?)。

so you will be able to initialize your repositories in Test environment with some test datasource (a mock?).

或者您可以使用一些模拟框架,例如EasyMock,用于创建要测试的存储库的部分模拟。 EasyMock默认情况下无需调用任何构造函数即可创建类的部分模拟。然后,您可以模拟 getDataSource()方法(希望您有一个方法,该方法可用于您需要访问数据源的任何地方?)以返回测试数据源,或者您可以可以使用Reflections设置最终的 ds 字段(我想是更糟糕的选择)。

Or you can use some mocking Framework, e.g. EasyMock, to create a partial mock of the Repository you want to test. EasyMock creates partial mocks of classes without calling any constructor by default. Then you could either mock the getDataSource() method (I hope you have one, that is used everywhere you need to access the datasource?) to return the test datasource, or you can set the final ds field using Reflections (the worse choice, I suppose).