java junit mockito_java-Junit Mockito没有按预期嘲笑

我试图通过模拟某些方法来编写单元测试.但是,我遇到了一些问题,其中我认为其中一个对象没有被嘲笑.

class A {

Class_C c;

Class A(String x) {

c = new Class_C(x);

}

public boolean internalMethod(String internalInput) {

// Some Logic

// Calls Inet4Address.getByName(internalInput)

}

public boolean method_to_be_tested(String input) {

boolean result_1 = internalMethod(input);

boolean result_2 = c.someMethod(result_1);

}

}

我写的单元测试如下:

@Test

public void test_method_to_be_tested() {

A testObj = new A("test_input");

testObj.c = Mockito.mock(Class_C.class);

A spyTestObj = Mockito.spy(testObj);

Mockito.when(spyTestObj.internalMethod(Mockito.anyString())).thenReturn(true);

Mockito.when(spyTestObj.c.someMethod(Mockito.anyBoolean())).thenReturn(true);

Mockito.when(spyTestObj.test_method_to_be_tested("test_input")).thenCallRealMethod();

Assert.assertTrue(spyTestObj.test_method_to_be_tested("test_input"));

}

我收到的错误指示Inet4Address.getByName()正在被调用.不应这样,因为我已经模拟了调用它的方法的输出.

解决方法:

Mockito.when将调用real方法.要解决此问题,可以改用Mockito.doReturn:

Mockito.doReturn(true).when(spyTestObj).internalMethod(Mockito.anyString());

Mockito.doReturn(true).when(spyTestObj.c).someMethod(Mockito.anyBoolean());

请注意,通常无需模拟对侦听对象的real方法-这始终是默认行为.

标签:unit-testing,junit,mockito,java

来源: https://codeday.me/bug/20191118/2025285.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值