---
title: "junit单元测试1： 数据库接口测试"
author: "baowp"
date: "2013-11-28T21:13:33Z"
tags: []
categories: ["编程语言"]
slug: "junit-1"
draft: false
lastmod: "2013-11-28T21:13:33Z"
id: 1982661
url: "https://baowp.iteye.com/blog/1982661"
---

开发应用程序，为了保证底层的代码质量，使应用容器启动后测试能够一次性通过，单元测试必不可少。

单测一般要测每一个service接口方法，这里以目前最流行的开源测试框架junit举个例子。

 

在工程的src/main/java下有个BookService interface

　　　

```
public interface BookService {

    int insert(BookEntity book);
}
```

 

 

在工程的src/test/java下同包目录中写一个BookServiceTest

```
package com.github.baowp.domain.service;

import com.github.baowp.domain.entity.BookEntity;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.transaction.TransactionalTestExecutionListener;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

/**
 * Created with IntelliJ IDEA.
 * User: baowp
 * Date: 11/27/13
 * Time: 3:06 PM
 * To change this template use File | Settings | File Templates.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "BookServiceTest-context.xml")//如果配置文件在同包名下,locations可以不声明

//以下两个注解与继承AbstractTransactionalJUnit4SpringContextTests等效，用于数据库事务回滚，继承后可不声明
@Transactional
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class, TransactionalTestExecutionListener.class})
public class BookServiceTest /*extends AbstractTransactionalJUnit4SpringContextTests*/ {

    @Resource
    private BookService bookService;

    @Test
    @Rollback(false)//表示不回滚事务，默认为true,该注解不写也默认回滚
    public void testInsert() {
        BookEntity book = new BookEntity();
        book.setTitle("title");
        book.setPrice(1.1f);
        int flag = bookService.insert(book);
        assertTrue(flag == 1);
        assertNotNull(book.getId());
    }
}
```

 

pom.xml引入

 

```
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-jdbc</artifactId>
		<version>${spring.version}</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-test</artifactId>
		<version>${spring.version}</version>
		<scope>test</scope>
	</dependency>
	<dependency>
		<groupId>junit</groupId>
		<artifactId>junit</artifactId>
		<version>4.11</version>
		<scope>test</scope>
	</dependency>
```

 

    这是一个简单的单元测试例子，一般用于直接的数据库操作测试，但如果一个service的方法非常复杂，里面还有涉及调用外部应用，这时就必须在单测方法先预设这种调用的返回值，也就是mock该接口。