单元测试Service使用mockito

发表于:2015-7-17 13:24

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:skykent    来源:51Testing软件测试网采编

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
  1、maven中添加
<!-- mockito -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>
<!-- junit 4 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
  2、要调用的service用@InjectMocks注解,service里面用@Mock注解
  @InjectMocks
  @Autowired
  private TestService testService;
  @Mock
  private TestMapper testMapper;
  3、用@Before初始化mock
  @Before
  public void init() throws Exception {
  MockitoAnnotations.initMocks(this);
  }
  4、模拟数据
  when(testMapper.getTestList()).thenReturn(list1);
  List<TestInfo> list = testService.getTestList();
  assertEquals("bname", list.get(0).getTest_name());
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号