我有一个需要测试的类A
。以下是A
的定义:
public class A {
public void methodOne(int argument) {
//some operations
methodTwo(int argument);
//some operations
}
private void methodTwo(int argument) {
DateTime dateTime = new DateTime();
//use dateTime to perform some operations
}
}
并且基于 dateTime
值,一些数据将被操作,从数据库中检索。对于此数据库,这些值通过 JSON 文件进行持久化。
这使事情变得复杂。我需要的是在测试时将 dateTime
设置为某个特定日期。有没有办法可以使用 mockito 模拟局部变量的值?
最佳答案
您不能模拟局部变量。但是,您可以做的是将其创建提取到 protected
方法并 spy
它:
public class A {
public void methodOne(int argument) {
//some operations
methodTwo(int argument);
//some operations
}
private void methodTwo(int argument) {
DateTime dateTime = createDateTime();
//use dateTime to perform some operations
}
protected DateTime createDateTime() {
return new DateTime();
}
}
public class ATest {
@Test
public void testMethodOne() {
DateTime dt = new DateTime (/* some known parameters... */);
A a = Mockito.spy(new A());
doReturn(dt).when(a).createDateTime();
int arg = 0; // Or some meaningful value...
a.methodOne(arg);
// assert the result
}
关于java - 使用 Mockito 模拟方法的局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23236338/