gpt4 book ai didi

java - Mockito - 验证一个方法是否调用同一类中的另一个方法

转载 作者:行者123 更新时间:2023-11-29 08:29:58 24 4
gpt4 key购买 nike

我正在尝试测试一个方法是否调用同一类中的另一个方法。示例:

public class Foo {

public void bar(String a){
switch(a) {
case "callBaz":
baz(a);
break;
case "callBat":
bat(a);
break;
default:
System.out.println("Input was " + a);
}
}

public void baz(String b){
System.out.println(b);
}

public void bat(String c){
System.out.println(c);
}
}

但是,如果我尝试对类本身进行 mockito 验证:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
public class FooTest {
@Test
public void testBazCalledFromBar(){
Foo foo = new Foo();
foo.bar("callBaz");
Mockito.verify(foo).baz("callBaz");
}
}

我得到异常:

org.mockito.exceptions.misusing.NotAMockException: 
Argument passed to verify() is of type Foo and is not a mock!
Make sure you place the parenthesis correctly!
See the examples of correct verifications:
verify(mock).someMethod();
verify(mock, times(10)).someMethod();
verify(mock, atLeastOnce()).someMethod();

使用模拟时: ...

@RunWith(SpringJUnit4ClassRunner.class)
public class FooTest {
@Test
public void testBazCalledFromBar(){
Foo fooMock = Mockito.mock(Foo.class);
fooMock.bar("callBaz");

Mockito.verify(fooMock).baz("callBaz");
}
}

我得到异常:

Wanted but not invoked:
foo.baz("callBaz");
-> at com.mn.stagportal.view.employee.FooTest.testBazCalledFromBar(FooTest.java:15)
However, there were other interactions with this mock:
foo.bar("callBaz");
-> at com.mn.stagportal.view.employee.FooTest.testBazCalledFromBar(FooTest.java:13)

有谁知道如何测试 baz("callBaz") 是否被调用?

最佳答案

这应该有效。

@RunWith(SpringJUnit4ClassRunner.class)
public class FooTest {
@Test
public void testBazCalledFromBar(){
Foo fooMock = Mockito.mock(Foo.class);
doCallRealMethod().when(fooMock).bar(anyString());
fooMock.bar("callBaz");

Mockito.verify(fooMock).baz("callBaz");
}
}

问题是,因为 fooMock 是一个 mock,当它遇到这一行时

fooMock.bar("callBaz");

它不知道该怎么做。您需要告诉 Mockito,您是要模拟方法调用还是要调用真实方法。

只有当代码流转到这个真正的方法并调用 baz 方法时,Verify 才能工作。

关于java - Mockito - 验证一个方法是否调用同一类中的另一个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49193423/

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