从Java junit测试模拟kotlin对象

时间:2019-01-04 14:37:54

标签: kotlin

我有这个科特琳物体

open class EnvironmentVars {
  val variables: Map<String, String>
    get() = System.getenv()
}

现在,我需要通过Java Junit测试对此进行测试,

@Mock
private EnvironmentVars environmentVars;

@Test
public void makeSureVarsCaseInsensitive() {
  LoaderFactory lf = new LoaderFactory();

  // setup the mock
  Map<String,String> myMap = new HashMap<>();
  myMap.put("ENV", "ok");

  when(environmentVars.getVariables()).thenReturn(myMap);

  // check caps
  assertEquals(lf.getEnv(environmentVars,"ENV"), "ok");

  // check lower
  assertEquals(lf.getEnv(environmentVars,"env"), "ok");
}

但是当我运行它时,我得到了

org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
   Those methods *cannot* be stubbed/verified.
   Mocking methods declared on non-public parent classes are not supported.
2. inside when() you don't call a method on mock but on some other object.

我认为这是因为getVariables在默认情况下是最终的。

有更好的方法吗?顺便说一句,我必须用Java编写单元测试。该应用程序的全部目的是证明Kotlin代码可以干扰

0 个答案:

没有答案