gavenkoa
gavenkoa

Reputation: 48723

Make a fake javax.sql.DataSource?

I have to write tests with String Test framework where many DB connections was used.

In test I don't need all data sources but Spring want them all to inject.

Are there any standard or well known fake javax.sql.DataSource implementation just to satisfy Spring DI mechanic?

Upvotes: 9

Views: 8120

Answers (5)

gavenkoa
gavenkoa

Reputation: 48723

This is my sample which does the job:

<!-- Create object with mocked parts that not used. -->
<bean id="config" class="org.Config">
    <constructor-arg>
        <bean class="org.mockito.Mockito" factory-method="mock">
            <constructor-arg value="javax.sql.DataSource"/>
        </bean>
    </constructor-arg>
    <property name="day" value="6"/>
</bean>

Update pom.xml with:

<dependency>
  <groupId>org.mockito</groupId>
  <artifactId>mockito-all</artifactId>
  <version>1.9.5</version>
  <scope>test</scope>
</dependency>

It works with:

<spring.version>3.0.0.RELEASE</spring.version>

Upvotes: 0

walkeros
walkeros

Reputation: 4942

Using Mockito (or other mocking framwork) is preferred (as pointed out in other answers). However if you just want to make your application context up (without complaining about data source), you can use org.springframework.jdbc.datasource.SimpleDriverDataSource.

You need to provide bean to the context with the name which overrides the original bean and make sure your fake bean is scanned first.

@Configuration
public class MyFakeConfig {

  @Bean(name = "NAME OF THE ORIGINAL BEAN TO OVERRIDE")
  public DataSource fakeDataSource() {
    return new SimpleDriverDataSource()

  }
}

Upvotes: 5

jhyot
jhyot

Reputation: 3955

You can use Spring's org.springframework.jdbc.datasource.AbstractDataSource which already provides some defaults for most of the interface methods. You only need to override two.

Upvotes: 2

Spacemonkey
Spacemonkey

Reputation: 1763

You can use Mockito framework. Using Springockito you can mock your datasources on a Spring environment.

Credit of this resource is for kubek2k in this SO answer.

Upvotes: 3

AlexR
AlexR

Reputation: 115328

I do not know well known DataSource mock. You can mock it yourself using one of mock frameworks (e.g. Mockito) but IMHO better solution is to use pure java in-memory database like H2, HSQLDB or Derby. You will get real data source with real data that you can fill in test code programmatically and simulate any situation that can happen in your production code.

Upvotes: 3

Related Questions