gpt4 book ai didi

java - 如何解决 实际上,Mockito 中与此模拟错误的交互为零

转载 作者:行者123 更新时间:2023-12-02 12:20:17 35 4
gpt4 key购买 nike

我正在尝试运行测试类,但抛出错误实际上有零交互

 class Xtractor{
void extractValues(request,Map m1, Map m2,Map m3){
//doesSomething..
}
}

class Sample{
public void extractMap(){
x.extractValues(request,m1,m2,m3);
}
}

class SampleTest{
@Mock
Xtractor xtractor;

@Mock
Sample sample;

@Before
public void setup(){
MockitoAnnotations.initMocks(this);
xtractor=mock(Xtractor.class);
ArgumentCaptor<Map> m1= ArgumentCaptor.forClass(Map.class);
ArgumentCaptor<Map> m2= ArgumentCaptor.forClass(Map.class);
ArgumentCaptor<Map> m3= ArgumentCaptor.forClass(Map.class);
ArgumentCaptor<HttpServletRequest> request=
ArgumentCaptor.forClass(HttpServletRequest.class);
}

@Test
public void testmapExtractor(){
Mockito.verify(xtractor).extractValues( request.capture(),m1.capture(),m2.capture(),m3.capture());
}
}

我大部分时间都在查看源代码,但无法得到上面测试类中缺少的内容

最佳答案

在您的测试用例中,您尝试验证是否调用了 xtractor.extractMap(),但您没有在测试中的任何位置调用该方法。 (附带说明:您在测试用例中引用的 extractMap 和您在示例代码中显示的 extractValues 之间存在一些混淆)。

假设 Sample 提供了 Xtractor 的实例,并且 Sample 公开了使用该 Xtractor 实例的公共(public)方法 然后您将在 Sample 上测试该公共(public)方法,如下所示:

public class Sample {

private Xtractor xtractor;

public Sample(Xtractor xtractor) {
this.extractor = extractor;
}

public void doIt(HttpServletRequest request, Map m1, Map m2, Map m3) {
x.extractValues(request,m1,m2,m3);
}
}

@Test
public void testmapExtractor() {
// create an instance of the class you want to test
Sample sample = new Sample(xtractor);

// invoke a public method on the class you want to test
sample.doIt();

// verify that a side effect of the mehod you want to test is invoked
Mockito.verify(xtractor).extractMap(request.capture(), m1.capture(), m2.capture(), m3.capture());
}

这个示例可以工作,尽管它看起来有点奇怪(您有一个名为 extractValues 的方法,其类型为 void ...Sample 您的问题中提供的类没有正文等),但本示例中已具备基本原理,即;

  • Xtractor 被 mock
  • Xtractor 的模拟实例被传递到 Sample
  • 示例已测试
  • SampleXtractor 的二次调用已验证

编辑 1:基于这些评论“即使此调用不在 Sample 类中,我也可以测试 xtractor.extractValues() ...好吧,在这里我将从 Xtractor 中删除 @Mock,我如何测试 xtractor.extractValues()”所需的答案可能是:

@Test
public void testmapExtractor() {
// create an instance of the class you want to test
Xtractor xtractor = new Xtractor();

// invoke a public method on the class you want to test
xtractor.extractValues();

// assert
// ...
// without knowing exactly what extractValues does it's impossible to say what the assert block should look like
}

关于java - 如何解决 实际上,Mockito 中与此模拟错误的交互为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45837655/

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