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);
      }
  }

测试结果
spring service层单元测试
我是二黑,关注我,每天分享测试干货内容~

上一篇:u-boot uclass_bind_device函数


下一篇:为什么技术需要在业务战略中发挥不可或缺的作用