Spring Boot's JUnit

Spring Boot's JUnit

 

      JUnit is used for unit testing, and it is also relatively important in actual development, because sometimes in order to check problems, test SQL or test some Service functions, using unit testing is faster than starting the project and clicking on the page.

 

Spring Boot implements unit testing

 

POM configuration for Spring Boot test

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

 

spring-boot-starter-test

Supports regular test dependencies, including JUnit, Hamcrest, Mockito and spring-test modules.

 

 

 

Taking DAO as an example, at least two configuration files are required

      1. Application: used to start Spring Boot

      2. DataSourceConfig: used to link the database



 

Spring Boot startup class

package com.cherrypicks.hsbcpayme.config;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;

@SpringBootApplication
@Import(DataSourceConfig.class)
@ComponentScan(basePackages = "com.cherrypicks.hsbcpayme.dao")
public class Application {
}

 

DataSourceConfig

package com.cherrypicks.hsbcpayme.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
public class DataSourceConfig {

    @Value("${spring.datasource.driverClassName}")
    private String driverClassName;
    @Value("${spring.datasource.url}")
    private String url;
    @Value("${spring.datasource.username}")
    private String userName;
    @Value("${spring.datasource.pwd}")
    private String pwd;
    
    @Bean
    public DataSource dataSource() {
         return tomcatPoolingDataSource();
    }

    private DataSource tomcatPoolingDataSource() {
        final org.apache.tomcat.jdbc.pool.DataSource dataSource = new org.apache.tomcat.jdbc.pool.DataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(userName);
        dataSource.setPassword(pwd);

        dataSource.setInitialSize(5); // The number of initial connections created when the connection pool starts (default value is 0)
        dataSource.setMaxActive(20); // The maximum number of simultaneous connections in the connection pool
        dataSource.setMaxIdle(12); // The maximum number of idle connections in the connection pool, the excess idle connections will be released, if set to a negative number, it means unlimited
        dataSource.setMinIdle(0); // The minimum number of idle connections in the connection pool, below this number a new connection will be created
        dataSource.setMaxWait(60000); // Maximum waiting time. When there is no available connection, the connection pool will wait for the maximum time for connection release. If the time limit is exceeded, an exception will be thrown. If -1 is set, it means infinite waiting
        dataSource.setRemoveAbandonedTimeout(180); // When the time limit is exceeded, useless (abandoned) connections are recycled
        dataSource.setRemoveAbandoned(true); // Whether to recycle useless connections (abandoned) after removeAbandonedTimeout is exceeded
        dataSource.setTestOnBorrow(true);
        dataSource.setTestOnReturn (true);
        dataSource.setTestWhileIdle(true);
        dataSource.setValidationQuery("SELECT 1");
        dataSource.setTimeBetweenEvictionRunsMillis(1000 * 60 * 30); // The interval for checking invalid connections is set to 30 minutes
        return dataSource;
    }

    @Bean
    public JdbcTemplate jdbcTemplate() {
        return new JdbcTemplate(dataSource());
    }

}

 

unit test class

package com.cherrypicks.hsbcpayme.dao;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.Assert;

import com.cherrypicks.hsbcpayme.config.Application;
import com.cherrypicks.hsbcpayme.dao.SystemConfigDao;
import com.cherrypicks.hsbcpayme.model.SystemConfig;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
public class SystemConfigDaoTest {

    @Autowired
    private SystemConfigDao systemConfigDao;

    @Test
    public void testGetByKey() {
        final SystemConfig systemConfig = systemConfigDao.getByKey("key");
        Assert.notNull(systemConfig);
        Assert.isTrue("value".equals(systemConfig.getConfigValue()));
    }

    @Test
    public void testFindAll() {
        Assert.notEmpty(systemConfigDao.findAll());
    }
}

 

@RunWith(SpringJUnit4ClassRunner.class) 

SpringJUnit support, thus introducing Spring-Test framework support!

 

@SpringApplicationConfiguration(classes = SpringBootSampleApplication.class) 

Specify the Application startup class of our SpringBoot project

 

@Test

method to run unit tests

 

 

 

Simple Spring Unit Testing

 

Previous Spring dependency

        <!-- unit test -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>

        <!-- spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
        </dependency>

 

No Spring boot classes are required, but the DataSource needs to be configured in XML

    <context:annotation-config />
    <context:component-scan base-package="com.cherrypicks.appsdollar.dao" />

    <!-- db2 source -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close" lazy-init="false">
        <property name="driverClass" value="${jdbc.driverClass}" />
        <property name="jdbcUrl" value="${jdbc.url}" />
        <property name="user" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="idleConnectionTestPeriod" value="60" />
        <property name="testConnectionOnCheckout" value="false" />
        <property name="initialPoolSize" value="2" />
        <property name="minPoolSize" value="10" />
        <property name="maxPoolSize" value="80" />
        <property name="acquireIncrement" value="1" />
        <property name="acquireRetryAttempts" value="1" />
        <property name="maxIdleTime" value="6000" />
        <property name="maxStatements" value="0" />
    </bean>

 

unit test class

package com.cherrypicks.appsdollar.dao;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import com.cherrypicks.appsdollar.base.model.enums.Lang;
import com.cherrypicks.appsdollar.base.test.JUnit4SpringTest;

public class CategoryDaoTest extends JUnit4SpringTest {

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private CategoryLangDao categoryLangDao;

    @Test
    public void findAppContent() {
        categoryLangDao.findByTitlePartyIdOsLang("asdfasdf", Lang.EN_US.toStringValue(), 1L, 1);
    }
}

 

 

compare the two

 

      1. Spring has less dependencies to write

      2. No need for XML configuration, use Java configuration instead

      3. Unit test classes, Spring replaces inheritance with annotations

 

 

 

reference:

http://blog.csdn.net/catoop/article/details/50752964

http://blog.sina.com.cn/s/blog_798f713f0102wiy5.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326475345&siteId=291194637