Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MOCK_CONTEXT报java.lang.NullPointerException #98

Closed
CZ-2020 opened this issue Feb 22, 2021 · 9 comments
Closed

MOCK_CONTEXT报java.lang.NullPointerException #98

CZ-2020 opened this issue Feb 22, 2021 · 9 comments
Labels
bug Something isn't working

Comments

@CZ-2020
Copy link

CZ-2020 commented Feb 22, 2021

No description provided.

@linfan
Copy link
Collaborator

linfan commented Feb 22, 2021

如果异常信息里有打印出错误堆栈,可以贴一下哦~

@CZ-2020
Copy link
Author

CZ-2020 commented Feb 22, 2021

没有其他信息,就报了个空指针异常

@linfan
Copy link
Collaborator

linfan commented Feb 22, 2021

是在什么地方使用了MOCK_CONTEXT呢,能否稍微详细描述一下?
Review了代码,MOCK_CONTEXT本身应该不能够造成空指针,目前也没有复现出这个问题

@CZ-2020
Copy link
Author

CZ-2020 commented Feb 23, 2021

我调试了一下在TestableClassTransformer类46行的transform方法出现的java/lang/reflect/InvocationTargetException
是junit-platform-commons-1.7.0.jar的ReflectionUtils类中invokeMethod方法在357行((Method)makeAccessible(method)).invoke(target, args)这里抛的异常

@CZ-2020
Copy link
Author

CZ-2020 commented Feb 23, 2021

下面这个代码就出现了
class BugRecoverTest {

@Test
void getStatus() {
    MOCK_CONTEXT.put("testName", "test1");
}

}
造成的原因是测试类内部没有mock任何方法,下面这个就没报错
class BugRecoverTest {

@Test
void getStatus() {
    MOCK_CONTEXT.put("testName", 1);
    System.out.println("ha");
}

public static class Mock {
    @MockMethod
    private Integer insertSelective(Object t) {
        return 1;
    }
}

}
另外如果用参数化测试注解,有mock方法也会抛异常
class BugRecoverTest {

@ParameterizedTest
@CsvSource({"test1", "test2"})
void getStatus(String testName) {
    MOCK_CONTEXT.put("testName", testName);
    System.out.println("ha");
}

public static class Mock {
    @MockMethod
    private Integer insertSelective(Object t) {
        return 1;
    }
}

}

@linfan
Copy link
Collaborator

linfan commented Feb 23, 2021

在没有关联Mock容器的测试类里使用MOCK_CONTEXT确实不行,因为这个类不会被TestableMock做预处理,实际场景来说,未关联Mock容器使用MOCK_CONTEXT也没有什么意义。参数化测试的问题是个BUG,我们会在近期版本修复。

感谢详细的代码例子👍

@linfan linfan added the bug Something isn't working label Feb 23, 2021
@yinfucheng
Copy link

在使用mockito的自动注入注解@mock@Injectable也会出现该npe的问题。

@linfan
Copy link
Collaborator

linfan commented Feb 24, 2021

mockito的自动注入注解导致NPE可以贴一个大概的示例吗,直接代码理解起来会直观一点

@linfan
Copy link
Collaborator

linfan commented Mar 3, 2021

参数化测试在v0.5.1已支持

@linfan linfan closed this as completed Mar 9, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

3 participants