我有一个需要测试的类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模拟局部变量的值?
发布于 2014-04-23 14:27:19
您不能模拟局部变量。但是,您可以将其创建内容提取到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
}
发布于 2014-04-23 14:29:54
处理此类问题的最佳方法是使用注入的Clock
服务,该服务用于获取DateTime的新实例。这样,您的测试可以注入一个模拟时钟,它返回一个特定的DateTime,而不是当前时间。
请注意,新的Java8time API专门为此目的定义了这样一个Clock class。
发布于 2019-08-08 05:21:35
这可能太麻烦了,但是如果您模拟可以提供局部变量的对象,则可以返回它的模拟。我不希望为了简化测试而重构代码,但这是值得考虑的事情。
public class A {
DateTimeFactory factory;
private void method() {
DateTime dateTime = factory.getDateTime();
//use dateTime to perform some operations
}
}
在您的测试中,您可以这样做:when(factoryMock.getDateTime()).doReturn(dateTimeMock)
工厂模拟需要以某种方式注入到类中。
https://stackoverflow.com/questions/23236338
复制相似问题