gpt4 book ai didi

java - 是否有一些方法在没有在模拟上调用的方法的情况下无法被 Mockito 模拟?

转载 作者:行者123 更新时间:2023-12-01 13:35:40 25 4
gpt4 key购买 nike

我是 Mockito 的新手,我认为它非常适合 mock 。我刚刚遇到了一种情况,我似乎无法让它工作 - 也就是说,用模拟方法替换普通对象的方法,没有 当我尝试模拟它时调用该方法。

这是我正在尝试做的一个 super 简化的示例,遗憾的是,它不会重复错误,但似乎与我的真实代码完全相同。

public class SimpleTest
{
public class A
{
}

public class B
{
public int getResult(A anObj)
{
throw new RuntimeException("big problem");
}
}

@Test
public void testEz()
{
B b = new B();
B spy = spy(b);

// Here are both of my attempts at mocking the "getResult" method. Both
// fail, and throw the exception automatically.

// Attempt 1: Fails with exception
//when(spy.getResult((A)anyObject())).thenReturn(10);

// Attempt 2: In my real code, fails with exception from getResult method
// when doReturn is called. In this simplified example code, it doesn't ;-(
doReturn(10).when(spy).getResult(null);
int r = spy.getResult(null);
assert(r == 10);
}
}

因此,当前当我运行测试时,当我尝试模拟 spy 的“getResult”方法时,测试会因抛出异常而失败。该异常是我自己的代码中的异常(即运行时异常),当我尝试模拟“getResult”方法=即执行上面的“doReturn”行时,就会发生这种情况。

请注意,我的实际用例当然更复杂......“B”类有很多其他方法,我想保留它们,只模拟一个方法。

所以我的问题是如何模拟它以便不调用该方法?

主要注意事项:我刚刚从头开始重写了整个测试,现在工作正常。我确信我在他们的某个地方有一个错误,但现在不存在了 - 当使用 spy 模拟该方法时,不会调用该方法!无论如何,我使用 doReturn 语法来模拟该方法。

doReturn(10).when(spy).getResult(null);

最佳答案

您重新编辑的问题现在工作得很好。

这行注释是错误的

when(spy.getResult((A)anyObject())).thenReturn(10);

应该是

when(spy.getResult(any(A.class))).thenReturn(10);

完整测试(未调用方法)

public class SimpleTest {

public class A {
}

public class B {
public int getResult(A anObj) {
throw new RuntimeException("big problem");
}
}

@Test
public void testEz() throws Exception {

B b = new B();
B spy = spy(b);

doReturn(10).when(spy).getResult(null);

int r = spy.getResult(null);

assert (r == 10);

}

}

结果

Tests Passed: 1 passed in 0,176 s

关于java - 是否有一些方法在没有在模拟上调用的方法的情况下无法被 Mockito 模拟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21292868/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com