带有局部变量的 Mockito

Mockito with local variables(带有局部变量的 Mockito)
本文介绍了带有局部变量的 Mockito的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我有一个返回 String 的简单方法.

I have a simple method that returns a String.

它还创建一个本地 List.我想测试添加到本地 List 的值.

It also creates a local List. I want to test the value added to the local List.

这是一个例子

package com.impl;

import java.util.ArrayList;
import java.util.List;

import com.test.domain.CustomerVo;

public class ClassImpl {

    public String assignGift(CustomerVo customerVo) {
        List<String> listOfGift = new ArrayList<String>();

        if (customerVo.getName().equals("Joe")) {
            listOfGift.add("ball");
        } else if ((customerVo.getName().equals("Terry"))) {
            listOfGift.add("car");
        } else if (customerVo.getName().equals("Merry")) {
            listOfGift.add("tv");
        }else {
            listOfGift.add("no gift");
        }

        return "dummyString";
    }
}

我如何测试当 customerVo.getName.equals("Terry"), car 被添加到本地 List 中.

How can I test that when the customerVo.getName.equals("Terry"), car is added to the local List.

推荐答案

这完全没那么容易.

您需要使用 powermock 之类的东西.

You need to use something like powermock.

使用 powermock,您可以在调用方法之前创建一个场景并播放它,这意味着您可以告诉 ArrayList 类构造函数预期被调用并返回一个 mock 而不是真正的ArrayList.

With powermock you create create a scenario before then method is called and play it back, this means you can tell the ArrayList class constructor to anticipate being called and return a mock rather than a real ArrayList.

这将允许您在 mock 上进行断言.

This would allow you to assert on the mock.

这样的事情应该可以工作:

Something like this ought to work:

ArrayList listMock = createMock(ArrayList.class);
expectNew(ArrayList.class).andReturn(listMock);

因此,当您的方法创建本地 List 时,powermock 实际上会返回您的模拟 List.

So when your method creates the local List powermock will actually return your mock List.

更多信息这里.

这种模拟实际上是为了对未编写为可测试的遗留代码进行单元测试.如果可以的话,我强烈建议重写代码,这样就不需要发生这种复杂的模拟了.

This sort of mocking is really for unit testing of legacy code that wasn't written to be testable. I would strongly recommend, if you can, rewriting the code so that such complex mocking doesn't need to happen.

这篇关于带有局部变量的 Mockito的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Sending a keyboard event from java to any application (on-screen-keyboard)(将键盘事件从 java 发送到任何应用程序(屏幕键盘))
How to make JComboBox selected item not changed when scrolling through its popuplist using keyboard(使用键盘滚动其弹出列表时如何使 JComboBox 所选项目不更改)
Capturing keystrokes without focus(在没有焦点的情况下捕获击键)
How can I position a layout right above the android on-screen keyboard?(如何将布局放置在 android 屏幕键盘的正上方?)
How to check for key being held down on startup in Java(如何检查在Java中启动时按住的键)
Android - Get keyboard key press(Android - 获取键盘按键)