简体   繁体   中英

How to mock a Datasource spring bean in class test

i want to test a class with a Datasource bean injected, but i don't know how to Mock the Bean Datasource(i dont' have the class but only bean configuration). My class is like this:

public class Configurazione {
    private DataSource dataSource;

    public DataSource getDataSource() {
       return dataSource;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }
    ...
 }

my beans:

<bean id="Configurazione" class="com.company.configurazione.Configurazione">
    <property name="dataSource" ref="dataSourceMySql" />
</bean>
<bean name="dataSourceMySql"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="..." />
    <property name="username" value="..." />
    <property name="password" value="..." />
</bean>

how can i test the class Configurazione with mockito and inject the datasource bean? i've no class DataSource to @mock in the test class Configurazione.

Usually for testing purposes additional Spring application context is created. And you can define beans differently there. For example you can use in-memory HSQL database as your datasource

  <jdbc:embedded-database id="dataSource" type="HSQL" >
    <jdbc:script location="scripts/ddl/sequences/*"/>
    <jdbc:script location="scripts/ddl/tables/*"/>
    <jdbc:script location="scripts/dml/*"/>
 </jdbc:embedded-database>

To use this snippet of code as-is you need to add hsql dependency to your project and adjust paths to scripts (these scripts create and populate database schema used in your tests). And you run your tests with that test application context

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