Jmockit单元测试及DBUnit集成测试搭建

所需pom依赖


    org.jmockit
    jmockit
    1.32
    test


    com.github.springtestdbunit
    spring-test-dbunit
    1.3.0
    test


    org.dbunit
    dbunit
    2.5.3


    org.springframework.boot
    spring-boot-starter-test
    test

基于JPA,则只要repository就行

Jmockit单元测试要避免使用到数据库。

@Mocked、@Injectable、@Tested、@Mock、MockUp、Expectations、Verification

DBUnit集成测试配置 @DatabaseTearDown、@DatabaseSetup、@ExpectedDatabase(只在增删改使用)



    
 
  

Test文件所需注解

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
@Transactional
@TestExecutionListeners({
        DependencyInjectionTestExecutionListener.class,
        DirtiesContextTestExecutionListener.class,
        TransactionalTestExecutionListener.class,
        MockitoTestExecutionListener.class,
        DbUnitTestExecutionListener.class
})
public class PersonDaoTest {

    @Autowired
    private UserRepository userRepository;

    @Test
    @DatabaseSetup({ "classpath:/dbunit/XmlDataSet.xml" })
    @DatabaseTearDown
//    @ExpectedDatabase(assertionMode= DatabaseAssertionMode.NON_STRICT,value="classpath:/MyTest_Result.xml")
        public void saveUser() throws Exception {
        Optional person = userRepository.findById(2);
        Assert.assertEquals("lisi",person.get().getName());
    }
}

这个配置类让xml文件允许空值

package com.jmockit.configuration;

import com.github.springtestdbunit.bean.DatabaseConfigBean;
import com.github.springtestdbunit.bean.DatabaseDataSourceConnectionFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
public class DBUnitConfiguration {

    private static final Logger LOGGER = LoggerFactory.getLogger(DBUnitConfiguration.class);

    @Bean
    public DatabaseConfigBean dbUnitDatabaseConfig() {
        DatabaseConfigBean bean = new DatabaseConfigBean();
        bean.setAllowEmptyFields(true);
        return bean;
    }

    @Bean
    public DatabaseDataSourceConnectionFactoryBean dbUnitDatabaseConnection(
            DatabaseConfigBean dbUnitDatabaseConfig,
            DataSource dataSource) {
        DatabaseDataSourceConnectionFactoryBean bean = new DatabaseDataSourceConnectionFactoryBean(dataSource);
        bean.setDatabaseConfig(dbUnitDatabaseConfig);
        return bean;
    }
}

 

 

你可能感兴趣的:(加油)