如何使Mockito模拟另一个文件中的常量?

时间:2019-01-08 18:59:15

标签: java testing mockito

编辑:我正在测试的方法调用在另一个类中定义的该常量,因此我想测试该方法是否独立于另一个类定义该常量的方式。我首先想到的是模拟它,但是我对如何以一种干净,安全的方式对其进行测试持开放态度。

(类,方法和变量名是通用的)

我试图弄清楚如何编写测试。 我的方法之一是从另一个类获取一个常量,如下所示:

OtherClass.CONSTANT

,此常量定义为:

public static final List<Long> CONSTANT =
  ImmutableList.of(1, 2);

在对该方法的测试中,我想模拟此调用。我已经尝试过

when(OtherClass.CONSTANT).thenReturn(ImmutableList.of(1, 2));

但这给了我这个错误:

RegularImmutableList cannot be returned by otherFunction()
otherFunction() should return String

otherFunction()是代码库中的其他一些功能,似乎与我一直在从事的任何事情都不相关。

我也尝试过

doReturn(ImmutableList.of(1, 2)).when(OtherClass.CONSTANT);

但是,您可能会猜到,它给了我这个错误:

Argument passed to when() is not a mock!
Example of correct stubbing:
doThrow(new RuntimeException()).when(mock).someMethod();

我对应该如何精确模拟此常量感到非常困惑。

1 个答案:

答案 0 :(得分:1)

您已经发现,您无法模拟常量的值。

最简单的方法可能是将设计转换为使用接口提供值,而不是直接使用值。

类似的东西:

interface ConstantSupplier {
    List<Long> get();
}

public MyClass(ConstantSupplier supplier) {
    this.supplier = supplier;
}

然后,您将对常量的引用替换为supplier.get()

现在很容易模拟:

ConstantSupplier supplier = mock(ConstantSupplier.class);
when(supplier.get()).thenReturn(List.of(4L, 9L));

您的非模拟代码可以使用lambda来提供实际值:

obj = new MyClass(() -> OtherClass.CONSTANT);