方法没有被嘲笑

问题描述 投票:1回答:1

我正在使用Mockito来模拟一个方法但测试正在运行真正的方法。

//Controller
@RestController
public class Controller {

    private Utils utils = new Utils();

    public String myMethod(String json){

        // Stuff gets done
        return utils.writeToKafka(topic, json, kafkatemplate, classname);

    }

我有一个看起来像这样的测试类:

//Test
@RunWith(SpringJUnit4ClassRunner.class)
public class ControllerTest {

    @Captor
    ArgumentCaptor<String> argumentCaptor;

    @Test
    public void processOSPUpdateRequested_test(){
         Controller controller = new Controller();
         Utils utils = Mockito.spy(new Utils());
         Mockito.doReturn("myResult").when(utils).writeToKafka(anyString(), anyString(), any(), anyString());

         String topic = controller.myMethod(myString);

         //Some assertions

我的writeToKafka方法签名是:

public String writeToKafka(String topic, String json, KafkaTemplate<String, String> kafkaTemplate, String classname)

但是,当我运行测试时,writeTokafka并没有被嘲笑!它运行实际的方法。为什么会这样?我错过了什么?

java unit-testing testing mocking mockito
1个回答
1
投票

你的问题的关键:你是newing Utils的一个实例,你不能从你的测试干净地得到它。

有两种方法可以解决这个问题 - 两者都来自于你是否想要使用模拟的哲学立场。两者都需要你注入Utils并使它成为某个地方的bean。

  1. 注入Utils并在测试中注入模拟,并放弃Spring测试运行器。 一旦你有了模拟,你可能想要改变你的测试不使用Spring跑步者,而是使用Mockito跑步者。 @RunWith(MockitoJUnitRunner.class) public class ControllerTest { @Mock private Utils utils; @InjectMocks private Controller testObj; // The rest of your test code }
  2. Utils作为定义的测试范围bean注入您的测试中,该bean展示您想要测试的行为。 这有点繁琐,但你有能力利用Spring测试运行器。我将此作为练习留给读者(基本上,一旦你编写了Utils bean,编写另一个用于测试并不困难)。
© www.soinside.com 2019 - 2024. All rights reserved.