spring service层单元测试

service层测试较简单,目前大多数测试主要是针对public方法进行的。依据测试方法划分,可以分为两种:基于mock的隔离测试和基于dbunit的普通测试。

mock隔离测试

配置pom.xml

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-all</artifactId>
    <version>1.10.19</version>
</dependency>

测试原理

隔离测试主要通过@Mock和@InjectMocks两个注解来实现模拟与被模拟。

@Mock:模拟出一个Mock对象,对象是空的,需要指明对象调用什么方法,传入什么参数时,返回什么值
@InjectMocks:依赖@Mock对象的类,也即是被测试的类。@Mock出的对象会被注入到@InjectMocks对象中

测试示例

被测类及方法

import com.agoura.agoura.entity.Members;
import com.agoura.agoura.mapper.MembersMapper;
import com.agoura.agoura.service.MembersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MembersServiceImpl implements MembersService {

    @Autowired
    private MembersMapper membersMapper;

    @Override
    public Members getMemberById(int id) {
        return membersMapper.selectByPrimaryKey(id);
    }
}

测试类及方法

import com.agoura.agoura.entity.Members;
import com.agoura.agoura.mapper.MembersMapper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:spring-mybatis.xml"})
public class MembersServiceTest {

    @Mock
    private MembersMapper membersMapper;

    @InjectMocks
    private MembersServiceImpl membersService;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testGetMembersById() {
        Members m = new Members(3, "wangwu", 1, 5, "12131232342");
        when(membersMapper.selectByPrimaryKey(3)).thenReturn(m);
        Members result = membersService.getMemberById(3);
        System.out.println(result);
        assertEquals(m, result);

        when(membersMapper.selectByPrimaryKey(Mockito.anyInt())).thenReturn(m);
        result = membersService.getMemberById(3);
        System.out.println(result);
        assertEquals(m, result);
    }
}

测试结果

测试结果截图

基于dbunit普通测试

unitils-dbunit测试直接模拟底层数据库中存储的内容,对service层进行测试的时候会直接连同DAO层一起测试。具体测试方法可以参考基于dbunit进行mybatis DAO层Excel单元测试

posted @ 2017-05-22 19:20  YGingko  阅读(15529)  评论(0编辑  收藏  举报