2017-07-03 99 views
0
的Mockito

所以我迁移少量的Java代码库科特林只是为了好玩,我已经迁移这个Java类:嘲讽科特林方法与Java +

public class Inputs { 
    private String engineURL; 
    private Map<String, String> parameters; 

    public Inputs(String engineURL, Map<String, String> parameters) { 
     this.engineURL = engineURL; 
     this.parameters = parameters; 
    } 

    public String getEngineURL() { 
     return engineURL; 
    } 

    public String getParameter(String key) { 
     return parameters.get(key); 
    } 
} 

这个科特林表示:

open class Inputs (val engineURL: String, 
        private val parameters: Map<String, String>) { 

    fun getParameter(key: String?): String { 
     return parameters["$key"].orEmpty() 
    } 

} 

但是现在我在使用Java编写的现有测试套件时遇到了一些麻烦。更具体地讲,我有这片单元测试使用的Mockito:

@Before 
public void setupInputs() { 
    inputs = mock(Inputs.class); 
    when(inputs.getEngineURL()).thenReturn("http://example.com"); 
} 

,并在when线路出现故障时,说

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 is not supported. 
2. inside when() you don't call method on mock but on some other object. 

有谁知道我怎么会做这项工作?我已经尝试在Kotlin版本上创建一个实际的getter(而不是依赖隐式getter),但到目前为止没有运气。

非常感谢! (如果你问自己,为什么我要从产品代码开始而不是测试,或者为什么我不使用mockito-kotlin,这些问题没有真正的答案。就像我说的,我只是为了迁移而迁移乐趣和希望,以显示我的团队其他开发人员是多么容易在实际项目中的语言)之间的互操作性

更新:我发现如果我添加when(inputs.getParameter("key")).thenReturn("value")相同的setupInputs()方法(inputs.getEngineURL())调用之前)我最终在Inputs#getParameter处发生了NullPointerException。 WTF?

+0

对于记录:这里的科特林代码缺少的getEngineUrl()方法。所以你的例子不是[mcve]。随时更新;那么我会觉得喜欢upvoting你的输入;-) – GhostCat

+0

@GhostCat我不知道我跟着它,毕竟'getEngineUrl()'是由基于'val engineURL:String'构造函数参数的Kotlin自动提供的,不是吗? – felipecao

+0

那么,你可能有一个点;-) – GhostCat

回答

1

没关系,我把他与两个错误消息,通过重写科特林版本是这样的:

open class TransformInputs (private val eURL: String, 
          private val parameters: Map<String, String>) { 

    open fun getParameter(key: String?): String { 
     return parameters["$key"].orEmpty() 
    } 

    open fun getBookingEngineURL(): String { 
     return eURL 
    } 

} 
+0

你也可以避免让你的课堂不必要地在Mockito 2中打开:http://hadihariri.com/2016/10/04/Mocking-Kotlin-With-Mockito/ –

+0

Thx @JKLy!我实际上已经考虑到了这一点,但我不想为了使其与Kotlin一起工作而更改现有的代码库。我的想法是向团队表明,使用Kotlin是可能的,只需要很少的更改,所以我故意忽略Mockito版本。 – felipecao