java 带有局部变量的 Mockito

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16506254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 23:10:02  来源:igfitidea点击:

Mockito with local variables

javaunit-testingjunitmockingmockito

提问by user1999453

I have a simple method that returns a String.

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

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

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

Here is an example

这是一个例子

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";
    }
}

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

customerVo.getName.equals("Terry"),car添加到本地List.

采纳答案by Boris the Spider

This isn't altogether that easy.

这完全没有那么容易。

You need to use something like powermock.

你需要使用类似powermock 的东西。

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

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

This would allow you to assert on the mock.

这将允许您在mock.

Something like this ought to work:

像这样的事情应该有效:

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

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

因此,当您的方法创建本地Listpowermock 时,实际上会返回您的 mock List

More information here.

更多信息在这里

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.

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