如何在Java Web应用程序中使用数据源测试DAO? [英] How to test DAO with DataSource in Java Web Application?

查看:148
本文介绍了如何在Java Web应用程序中使用数据源测试DAO?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Tomcat 7 JSP Servlets 执行项目。 code>, Log4j MySQL

I'm doing my project using Tomcat 7, JSP, Servlets, Log4j and MySQL.

我已经在这个问题上搜索了几个小时,没有给出正确的答案。

I've googled this question for hours with no proper answer.

如何使用 DataSource 测试我的DAO和 JUnit 吗?

How can I test my DAO's using DataSource and JUnit ?

我发现了这个文章最近发布,但不知道如何针对我的目的对其进行配置,并且不确定这样做是否是一种好方法。

I found this article recently, but don't know how to configure it for my purposes and don't sure if it's a good way of doing it.

我具有以下DAO层次结构:

I'm having the following DAO hierarchy:

我正在 AbstractRepository DataSource >以下方式:

And I'm obtaining the DataSource in AbstractRepository in the following way:

...
protected final DataSource ds;
...
    public AbstractRepository() {
        DataSource dataSource = null;
        try {
            Context initContext = new InitialContext();
            dataSource = (DataSource) initContext
                    .lookup("java:/comp/env/jdbc/mydb");
        } catch (NamingException ex) {
            LOG.error("Cannot obtain a connection from the pool", ex);
        }
        ds = dataSource;
    }
...

您是否会生成这种方式的代码示例解决此问题的方法,例如用于入口存储库测试

Would you produce some code sample of the way to solve this problem for example for Entrant Repository Test?

推荐答案

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).

这篇关于如何在Java Web应用程序中使用数据源测试DAO?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆