问题描述
我有一个返回 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!