如何存根 Mockito 测试类的私有方法

编程入门 行业动态 更新时间:2024-10-20 09:29:56
本文介绍了如何存根 Mockito 测试类的私有方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我们有一个名为 SomeClass 的 Java 类

Say we have java class called SomeClass

public class SomeClass { private boolean isMethod() { return false; } public void sendRequest(String json, String text) { int messageId; if (isMethod()) { messageId = getMessageId(json); sendMessage(messageId, text); } else { throw new IllegalArgumentException(); } } private void sendMessage(int messageId, String text) { } private int getMessageId(String text) { Pattern p = Patternpile("messageId=(\\d+)&"); Matcher m = p.matcher(text); if (m.find()) { return Integer.valueOf(m.group(1)); } return 0; } }

不要在意方法的名字,它们都是可选的.

Don't pay attention to methods' name, they're all optional.

  • 我想单独测试 sendRequest(String json, String text) 方法.
  • 我想存根方法 isMethod() 和 getMessageId(json),并验证 sendMessage(messageId, text) 方法被调用.
  • 我需要确保 getMessageId(json) 返回 25 并且 isMethod() 无论给出哪个参数值都返回 true.
  • I want to test sendRequest(String json, String text) method in isolation.
  • I want to stub methods isMethod() and getMessageId(json), and verify that sendMessage(messageId, text) method is called.
  • I need to be sure that getMessageId(json) returns 25 and that isMethod() returns true no matter which argument value given.
推荐答案

这可以通过 PowerMockito 框架来实现.

This could be achieved by PowerMockito framework.

import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; @RunWith(PowerMockRunner.class) @PrepareForTest(SomeClass.class) public class SomeClassTest { private SomeClass someInstance; @Before public void setUp() throws Exception { someInstance = PowerMockito.spy(new SomeClass()); } @Test public void sendRequest() throws Exception { String json = "JSON"; String text = "Some text"; int messageId = 1; PowerMockito.doReturn(true).when(someInstance, "isMethod"); PowerMockito.doReturn(messageId).when(someInstance, "getMessageId", json); someInstance.sendRequest(json, text); PowerMockito.verifyPrivate(someInstance).invoke("isMethod"); PowerMockito.verifyPrivate(someInstance).invoke("getMessageId", json); PowerMockito.verifyPrivate(someInstance).invoke("sendMessage", messageId, text); } }

更多推荐

如何存根 Mockito 测试类的私有方法

本文发布于:2023-10-31 04:44:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545042.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:存根   测试   方法   Mockito

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!