本篇内容主要讲解“java中PowerMockito模拟方法内new对象实例”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“java中PowerMockito模拟方法内new对象实例”吧!
在做单元测试中有时候需要对方法内new出来的对象进行隔离,这是我们需要使用PowerMockito。
添加依赖
<dependency> <groupId>org.powermock</groupId> <artifactId>powermock-module-junit4</artifactId> <version>1.7.4</version> <scope>test</scope> </dependency> <dependency> <groupId>org.powermock</groupId> <artifactId>powermock-api-mockito</artifactId> <version>1.7.4</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>1.10.19</version> <scope>test</scope> </dependency>
注意:版本要对应一致,不同的版本可能出现启动失败!
被测试类
@Slf4j @Component public class UserService { @Autowired private UserMapper userMapper; public User userCreate(String name, String password) throws BusinessException { User user = userMapper.query(name, password); if(user == null){ user = new User(); user.setName(name); user.setPassword(password); user.setGroup(1); user.setCreateTime(new Date()); TokenApi tokenApi = new TokenApi();//测试时需要隔离此类,此类依赖其他服务! try { user.setToken(tokenApi.getToken()); } catch (Exception e) { throw new BusinessException("-2","获取token失败"); } try { userMapper.create(user); } catch (Exception e) { throw new BusinessException("-1","系统异常"); } } return user; } }
测试类
@RunWith(PowerMockRunner.class) @PrepareForTest({UserService.class})//此注解内配置的是需要mock的new对象代码所在的类 public class UserServiceTest { @InjectMocks private UserService userService; @Mock private UserMapper userMapper; private TokenApi tokenApi; @Test public void userCreate(){ String name = "xiaoming"; String password = "000000"; when(userMapper.query(name, password)).thenReturn(null); tokenApi = PowerMockito.mock(TokenApi.class); try { PowerMockito.whenNew(TokenApi.class).withNoArguments().thenReturn(tokenApi); } catch (Exception e) { e.printStackTrace(); } PowerMockito.when(tokenApi.getToken()).thenReturn("11111111"); User user = userService.userCreate(name, password); assertEquals(name,user.getName); assertEquals("11111111",user.getToken()); } }
when() 跟 PowerMockito.when() 是两个不同的方法!when() = Mockito.when()
到此,相信大家对“java中PowerMockito模拟方法内new对象实例”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。