简体   繁体   中英

How to call datasource in Junit

I have a maven WAR package with JSF pages. Usually I use

@Resource(name = "jdbc/Oracle")
    private DataSource ds;

to call database when I deploy the WAR package on Glassfish server. But in case of JUnit tests when I build the package on my laptop with netbeans I cannot use this datasource. How I can solve this problem? I want to run the JUnit tests with database tables right after I build the package but I don't have a datasource. What are the possible solutions?

Do you actually want to run your unit tests against the database? Personally I would try to avoid this, since it usually ties the test too closely to the state of the database and often prevents you from actually testing the "unit" and all the possible states you might like to handle. It will also probably make your unit tests take some time to run, which is not ideal.

An alternative would be to create a mock DataSource , using for example EasyMock or Mockito . Or you could create your own mock implementation of the DataSource interface, if you know you would like to define some common behaviour for DataSources across many tests.

If you really want to use the database, you would have to look at manually instantiating whatever implementation of DataSource you are using (eg OracleDataSource ) and then using this in your class.

In either case, you will probably have to switch to using constructor or method injection to make it a bit easier to set the DataSource on the instance you are testing. (Otherwise you will have to use reflection to set the private variable.)

For example, your class might look like this:

public class DatabaseOperations {
    private DataSource dataSource;

    @Resource(name = "jdbc/Oracle")
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }
}

And then your test might look like this:

public class DatabaseOperationsTest {
    public void testSomeOperation() {
        DatabaseOperations databaseOperations = new DatabaseOperations();
        databaseOperations.setDataSource(new MockDataSource());
    }
}

If you really do need to run tests using an injected DataSource, you could consider using Arquillian which will create a deployment unit for you, deploy it to either an embedeed or remote Glassfish container, together with a configured DataSource specifically for testing if you wish. They have a guide for this specific scenario.

The advantage is that you will have a full-blown container with CDI. You control what gets package so you can provide test stubs for CDI classes. You can also control the deployment configuration (test vs. production configuration). It is non-invasive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM