如何在 java 中存根单个方法以进行单元测试?

发布于 2024-07-26 00:49:58 字数 225 浏览 3 评论 0原文

我在一个类中有一个方法正在写入某个字符串,该方法调用另一个执行相同操作的方法。 例如:

void foo() {
  a += "xyx";
  bar();
}

void bar() {
  a += "abc";
}

出于单元测试的目的,我想分别测试 foo 和 bar。 当我调用 foo() 或用其他方法替换它时,有什么方法可以阻止 bar 运行吗?

I've got a method in a class that's writing to some string, which calls another method which does the same. Something like:

void foo() {
  a += "xyx";
  bar();
}

void bar() {
  a += "abc";
}

For unit testing purposes, I want to test foo and bar separately. Is there any way to prevent bar from being run when I call foo() or to replace it with another method?

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

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

发布评论

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

评论(3

猫腻 2024-08-02 00:49:58

创建一个覆盖 bar() 的子类,该子类不执行任何操作。

Create a subclass that overrides bar() that does nothing.

冷默言语 2024-08-02 00:49:58

你为什么想这么做?

您可以使用方面在字节代码级别拦截代码(不明智); 您可以接受一个调用 bar 的对象: void foo(MyBarObject m) {
a+=“xyx”;
m.bar();
但是,正如

我所说,我不明白为什么这有用。 单元测试旨在测试公共接口。 如果 bar() 是私有的或受保护的,那么它会通过您对 foo() 的调用以及稍后的断言自动进行测试。 如果 foo() 和 bar() 都是公共的,那就分别测试它们吧。

你能发布一个真实的例子吗? 您可以更改正在测试的代码吗? ETC。

Why would you want to do that?

You could intercept the code at the byte code level using aspects (not wise); you could take in an object that calls bar: void foo(MyBarObject m) {
a += "xyx";
m.bar();
}

But, as I said, I can't think why this is useful. A unit test is meant to test a public interface. If bar() is private or protected, then it's tested automatically via your call, and later assertions, to foo(). If both foo() and bar() are public, cool, test them separatley.

Can you post a real example? Can you change the code under test? Etc.

挽手叙旧 2024-08-02 00:49:58

有人可能会说上面的例子不是可测试的代码。 相反,如果代码是:

void foo() {
  a += "xyx";
}

void bar() {
  a += "abc";
}

void fooBar() {
  foo();
  bar();
}

将很容易进行单元测试。

One could argue that the above example isn't testable code. Instead, if the code were:

void foo() {
  a += "xyx";
}

void bar() {
  a += "abc";
}

void fooBar() {
  foo();
  bar();
}

it would be easy to unit test.

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