使用ReflectionTestutils.invokeMethod调用私人方法的问题

发布于 2025-01-23 13:37:00 字数 2760 浏览 4 评论 0 原文

我正在为 method_a 编写一个快乐的路径单元测试调用私有方法 method_b
该服务基于Springboot Framework和Java8。
Junit5和Mockito用于单位测试。

以下是基本的代码结构,对不起,无法显示原始代码。

public class SomeClass {

public boolean method_a(obj obj_data) {
    ...

    Optional<String> str;
    str = method_b(str_1);
    
    if(!str.isPresent()) {
        return false;
    }

    ...

    return true;
}

private Optional<String> method_b(String str) {
    ...
    try {
        ...
        return Optional.of(thirdPartCtrl.method_c(val_1));
    }
    cathch (Exception exception) {
        ...
        return Optional.empty();
    }
}
}

以下是单元测试代码:
agky_1:

@Test
void test method_a() {
...
when(ReflectionTestUtils.invokeMethod(SomeClassMock,"method_b", "str_input")).thenReturn(Optional.of("validData"));

...
assertTrue(SomeClass.method_a(val));
}

agky_2:

@Test
void test method_a() {

...
doReturn(Optional.of("validData")).when(ReflectionTestUtils.invokeMethod(SomeClassMock,"method_b", "str_input"));
...
assertTrue(SomeClass.method_a(val));
}

我注意到,当我运行单元测试时, java.lang.nullpoInterException 始终是从行 return return> return odional.of(thixpartctrl.method_c(val_1))生成的。在私有方法 method_b

当前问题是:
如果我不使用 reflectionTestutils.invokemethod 来调用私有 method_b someclass.method_a(val)始终将返回false。

通过使用,

when(ReflectionTestUtils.invokeMethod(SomeClassMock,"method_b", "str_input")).thenReturn(Optional.of("validData"));

我将

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
Optional cannot be returned by convert()
convert() should return NotificationRequestDetails

***

If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. This exception *might* occur in wrongly written multi-threaded tests.
   Please refer to Mockito FAQ on limitations of concurrency testing.
2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - 
   - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.

如果我使用的话,

doReturn(Optional.of("validData")).when(ReflectionTestUtils.invokeMethod(SomeClassMock,"method_b", "str_input"));

获得错误:

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

我对 reflectionTestutils.invokemethod
我做错了什么。 有没有更好的方法模拟私人方法返回有效值?
任何建议都对此表示赞赏!谢谢你!

I am writing a happy path unit test for method_a which calling a private method method_b.
The service is based on springboot framework and java8.
Junit5 and Mockito are used for unit test.

Following are the basic code structure, sorry can't show the original code.

public class SomeClass {

public boolean method_a(obj obj_data) {
    ...

    Optional<String> str;
    str = method_b(str_1);
    
    if(!str.isPresent()) {
        return false;
    }

    ...

    return true;
}

private Optional<String> method_b(String str) {
    ...
    try {
        ...
        return Optional.of(thirdPartCtrl.method_c(val_1));
    }
    cathch (Exception exception) {
        ...
        return Optional.empty();
    }
}
}

Following are the unit test code:
approach_1:

@Test
void test method_a() {
...
when(ReflectionTestUtils.invokeMethod(SomeClassMock,"method_b", "str_input")).thenReturn(Optional.of("validData"));

...
assertTrue(SomeClass.method_a(val));
}

approach_2:

@Test
void test method_a() {

...
doReturn(Optional.of("validData")).when(ReflectionTestUtils.invokeMethod(SomeClassMock,"method_b", "str_input"));
...
assertTrue(SomeClass.method_a(val));
}

I noticed that when I run the unit test, java.lang.NullPointerException was always generated from line return Optional.of(thirdPartCtrl.method_c(val_1)); in the private method method_b

Current issue is:
If I do not use ReflectionTestUtils.invokeMethod to invoke the private method_b, SomeClass.method_a(val) will always return false.

By using

when(ReflectionTestUtils.invokeMethod(SomeClassMock,"method_b", "str_input")).thenReturn(Optional.of("validData"));

I will get error

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
Optional cannot be returned by convert()
convert() should return NotificationRequestDetails

***

If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. This exception *might* occur in wrongly written multi-threaded tests.
   Please refer to Mockito FAQ on limitations of concurrency testing.
2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - 
   - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.

If I use

doReturn(Optional.of("validData")).when(ReflectionTestUtils.invokeMethod(SomeClassMock,"method_b", "str_input"));

will get error:

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

What did I do wrong with ReflectionTestUtils.invokeMethod?
Is there a better way to mock the private method to return a valid value?
Any suggestion are appreciated! Thank you!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

思念绕指尖 2025-01-30 13:37:00

如何测试私人方法?如何模拟私人方法?这些是不同的概念。您似乎将它们混合在一起。

如果要测试私有方法,则使用ReflectionTestutils直接调用私有方法

https://roytuts.com/how-to-to-to-te-t-t-t-tes-tes-tep-t-tes-tes-com/how-to-t-test, -private-methods-using-junit-5/

当您测试公共方法A时,该方法称为私有方法B,私有方法B将自动称为同一类。嘲笑私人方法的返回。这在Mockito中是不可能的。

解决方法1:
将私有访问修饰符更改为默认
通过使用间谍

Workaround 2:
重构私有方法B到B类中的公共方法,

我们也无法模拟注射剂对象的私人方法。您可能需要进行解决方案2
https://stackoverflow.com/questions/64565726/how-to-mock-a-private-method-under-a-注射液 - java级别的级别:〜:text = tldr%3b%20 you%20 cannot%20use%20 IndigtsMocks,逻辑%20in%20 Your%20 Your%20Java%20Java%20Project

How to test private method? How to mock a private method? These are different concepts. You seem to mix them together.

If you want to test private method, you'd call private method directly from your test case by using ReflectionTestUtils.

https://roytuts.com/how-to-test-private-methods-using-junit-5/

When you test public method a, which would call private method b, the private method b would be called automatically assuming both methods are in same Class A. So you might want to mock the return of private method. This is impossible in Mockito.

Workaround 1:
Changing private access modifier to default
Partially mock testing object by using spy

https://lkrnac.net/blog/2014/01/mock-private-method/#mock-private-method

Workaround 2:
Refactor private method b to public method in Class B

Also we can't mock private method for Injectmock object. You might need to go with workaround 2
https://stackoverflow.com/questions/64565726/how-to-mock-a-private-method-under-a-injectmocks-annotated-class-in-java#:~:text=TLDR%3B%20you%20cannot%20use%20InjectMocks,logic%20in%20your%20java%20project.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文