简体   繁体   English

Mockito 在模拟 Javalin 上下文中调用真实方法

[英]Mockito calling real method on mocked Javalin context

I have a real strange behavior going on.我有一个真正奇怪的行为。 It seems that Mockito is calling the real method on a mocked class, resulting in a NullPointerException.似乎 Mockito 正在模拟 class 上调用真实方法,从而导致 NullPointerException。 I am mocking the Context object present in the Javalin http framework for Java.我是 mocking 上下文 object 存在于 Javalin http 框架中的 ZD52387880E1EA22817A9Z2D7

This is the minimal code that results in an exception.这是导致异常的最少代码。

import io.javalin.http.Context;
import org.mockito.Mockito;

public class Main {
    public static void main(String[] args) {
        Context ctx = Mockito.mock(Context.class);
        Mockito.when(ctx.queryParam("hello")).thenReturn("test");
    }
}

I get我明白了

    at io.javalin.http.Context.queryString(Context.kt:285)
    at io.javalin.http.Context.queryParamMap(Context.kt:282)
    at io.javalin.http.Context.queryParams(Context.kt:279)
    at io.javalin.http.Context.queryParam(Context.kt:266)
    at io.javalin.http.Context.queryParam$default(Context.kt:266)
    at io.javalin.http.Context.queryParam(Context.kt)
    at Main.main(Main.java:9)

But its not supposed to call the real code?但它不应该调用真正的代码? What is going on?到底是怎么回事?

You're not really adding tests correctly.您并没有真正正确地添加测试。 Instead of creating them in the main method, create a test class and then annotate your tests with the @Test annotation (will need JUnit for this).不要在 main 方法中创建它们,而是创建一个测试 class 然后使用@Test注释来注释您的测试(为此需要 JUnit)。 You should then be able to run the tests using your IDE.然后,您应该能够使用 IDE 运行测试。

Yes I know that I am supposed to use this in a test.是的,我知道我应该在测试中使用它。 I just showed that snipped to show what does not work.我只是展示了剪断以显示什么不起作用。 The fault here turned out to be that Mockito is written in Kotlin which by default makes all methods final when exposing a Java api. The fault here turned out to be that Mockito is written in Kotlin which by default makes all methods final when exposing a Java api. Mockito does not work with final methods and that is why this does not work. Mockito 不适用于 final 方法,这就是为什么这不起作用。 You simply can't mock Kotlin frameworks with Mockito, you have to use something else.你根本不能用 Mockito 模拟 Kotlin 框架,你必须使用别的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM