Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

unit testing - How to test DAO with DataSource in Java Web Application?

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

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

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.

I'm having the following DAO hierarchy: dao hierarchy

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...