使用Mockito模拟方法的局部变量
我有一个需要经过测试的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 }
处理此类问题的最佳方法是使用注入的Clock
服务,用于获取DateTime的新实例。 这样,你的测试可以注入一个模拟Clock,它返回一个特定的DateTime而不是当前时间。
请注意,新的Java 8时间API定义了这样一个Clock类 ,专门用于此目的。