Mockito 不是在嘲笑电话
我正在测试的功能之一是通过 ssh 连接到一台机器。我想模拟 ping 方法,它实际上尝试 ssh 进入机器,因为我并没有真正 ssh 进入机器。
我正在测试的类:
public class TestMachine {
public int ping(host){
}
public boolean machineIsGood(host) {
blah blah
int val = ping(host);
blah blah blah
if(val != 0) return false;
return true;
}
}
测试类是这样的:
public class TestClass {
public void setUp() {
TestMachine tester = spy(new TestMachine());
}
public void testOne() {
when(test.ping(anyString()).thenReturn(-1);
assertFalse(tester.machineIsGood("testHost"));
}
{
问题是,当我在本地运行它们时,它们工作得很好,但在我们的自动构建系统上,它似乎实际上是在调用真正的 ping 并获得身份验证异常。 我将使用mock()而不是spy(),因为我读到它有点奇怪,但我只是不明白是什么造成了差异,因为它实际上是在调用该方法!只是想知道其他人是否有任何见解。
One of the functions I'm testing is sshing into a machine. I want to mock the ping method, that actually tries to ssh into a machine, since I am not really sshing into a machine.
class I am testing:
public class TestMachine {
public int ping(host){
}
public boolean machineIsGood(host) {
blah blah
int val = ping(host);
blah blah blah
if(val != 0) return false;
return true;
}
}
The test class goes something like this:
public class TestClass {
public void setUp() {
TestMachine tester = spy(new TestMachine());
}
public void testOne() {
when(test.ping(anyString()).thenReturn(-1);
assertFalse(tester.machineIsGood("testHost"));
}
{
The problem is that when I am running them locally, they work just fine, but on our autobuild system it seems like it is actually calling the real ping and getting an Authentication Exception.
I'm going to use mock() instead of spy() since I've read it's a bit weird, but I just can't understand what makes a difference in that it is actually calling the method! Just wondering if anyone else has any insight.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据我的经验,您不应该使用模拟来测试同一类中方法之间的交互。
这告诉我们,您应该将您的 SUT(被测系统)与需要用测试替身(您不想在单元测试中“真正”调用的 ping)替换的外部依赖项分离。
华泰
In my experience, you should not use mocks to test interactions between methods in the same class.
What this tells us is that you should decouple your SUT (system under test) from the external dependency that you need to replace with a test double (the ping that you do not want to call "for real" in your unit tests).
HTH
当您使用 Mockito.spy() 时,请对非 void 方法使用 Mockito.doReturn() 或对 void 方法使用 Mockito.doNothing() 。
在你的情况下:
When you use Mockito.spy(), use the Mockito.doReturn() for non-void methods or Mockito.doNothing() for void methods.
In your case: