如何模拟Java中特定方法的响应?

发布于 2025-02-08 03:19:01 字数 446 浏览 1 评论 0原文

我有这样的课程

public class Foo {

 public String getData(String id) {
    JsonObject json = this.somePrivateMethod(id);
    String d = // some manipulation
    return d;
 }
 private JsonObject somePrivateMethod(String id) {
 
   
 }
}

,我正在尝试编写getData的单元测试 现在,我想用两个jsons模拟此SomePrivateMethod

goodJson = {1: 2}, badJson = {"foo" : "bar"}

如何在Java中模拟该私人方法。

I have a class like this

public class Foo {

 public String getData(String id) {
    JsonObject json = this.somePrivateMethod(id);
    String d = // some manipulation
    return d;
 }
 private JsonObject somePrivateMethod(String id) {
 
   
 }
}

I am trying to write the unit test for getData
Now, I want to mock this somePrivateMethod with two jsons

goodJson = {1: 2}, badJson = {"foo" : "bar"}

How do I mock that private method in java.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

青丝拂面 2025-02-15 03:19:01

您可以使用Mockito之类的框架来实现模拟。

when(good.getData()).then(json)

因此,当您的测试案例运行以及遇到getData()方法时,它会从the()方法响应JSON对象

You can use frameworks like Mockito to achieve the mocking.

when(good.getData()).then(json)

So when your test case runs and when it encounters getData() method then it responses the json object from the then() method

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文