junit 5使用obsconstruction()。dessetting()。useconstructor()而不是powermock.whennew()。

发布于 2025-02-02 03:06:37 字数 2594 浏览 2 评论 0原文

现在,我想使用Junit 5 + Mockito 4.x版本 + Mockito-Inline 4.x版本,而不是Junit 4 + PowerMock 2.0.9,

因为Junit 5不支持PowerMock PowerMock也可以使用Mockito-Inline可以模拟静态,看起来像它不再需要PowerMock。

但是,当我使用Mockito模拟静态时,我想使用相同的效果,例如powermock.whennew(xxx.class).withargument(1,2,3,4)。

这是我的代码的一部分,它可以起作用。

    @Test
    void get_report_page() {
        ReportPageRequest reportPageRequest = prepare_request();
        prepare_reportPage(context, 9999L, pageable);

        when(reportConverter.toReportSpecification(user, reportPageRequest)).thenReturn(reportSpecification);
        when(PageRequest.of(1, 100)).thenReturn(pageRequest);
        when(reportRepository.findAll(reportSpecification, pageRequest)).thenReturn(reportPage);
        when(reportConverter.toReportPageResponse(context)).thenReturn(reportPageResponses);
        pageMockedConstruction = Mockito.mockConstruction(PageImpl.class,
                withSettings().useConstructor(reportPageResponses, pageable, 9999L), (mock, context) -> {
                    when(mock.getTotalElements()).thenReturn(123456L);
                    when(mock.getTotalPages()).thenReturn(1);
                    when(mock.getContent()).thenReturn(reportPageResponses);
                });

        Page<ReportPageResponse> actual = sut.getReportPage(user, reportPageRequest);

        assertThat(actual.getTotalElements()).isEqualTo(123456L);
        assertThat(actual.getTotalPages()).isEqualTo(1);
        assertThat(actual.getContent()).isEqualTo(reportPageResponses);
    }
}

我的问题是我可以验证模拟静态对象的行为,但是无法验证结果,这是我的尝试

pageMockedConstruction = Mockito.mockConstruction(PageImpl.class,
                withSettings().useConstructor(reportPageResponses, pageable, 9999L), (mock, context) -> {
                    when(mock.getTotalElements()).thenReturn(123456L);
                    when(mock.getTotalPages()).thenReturn(1);
                    when(mock.getContent()).thenReturn(reportPageResponses);
                });

        // I thought here will be the same mock object
        // when expected and actual will throught the Mockito.mockConstruction, but actually generate the different object
        PageImpl<ReportPageResponse> expected = new PageImpl<>(this.reportPageResponses, pageable, 9999L);
        Page<ReportPageResponse> actual = sut.getReportPage(user, reportPageRequest);

        // Here will be wrong, because actual and expected has different hashCode
        Assertions.assertThat(actual).isEqualTo(expected);

研究很多文章,但我找不到答案。

有人遇到同样的问题吗?

Now I want to use Junit 5 + Mockito 4.x version + Mockito-inline 4.x Version instead of Junit 4 + PowerMock 2.0.9

Because the Junit 5 doesn't support PowerMock also Mockito-inline can mock static, look like it doesn't need PowerMock anymore.

But when I use Mockito mock static, I want to use the same effect like Powermock.whenNew(xxx.class).withArgument(1,2,3,4).thanReturn(someThing).

This is part of my code and it can work.

    @Test
    void get_report_page() {
        ReportPageRequest reportPageRequest = prepare_request();
        prepare_reportPage(context, 9999L, pageable);

        when(reportConverter.toReportSpecification(user, reportPageRequest)).thenReturn(reportSpecification);
        when(PageRequest.of(1, 100)).thenReturn(pageRequest);
        when(reportRepository.findAll(reportSpecification, pageRequest)).thenReturn(reportPage);
        when(reportConverter.toReportPageResponse(context)).thenReturn(reportPageResponses);
        pageMockedConstruction = Mockito.mockConstruction(PageImpl.class,
                withSettings().useConstructor(reportPageResponses, pageable, 9999L), (mock, context) -> {
                    when(mock.getTotalElements()).thenReturn(123456L);
                    when(mock.getTotalPages()).thenReturn(1);
                    when(mock.getContent()).thenReturn(reportPageResponses);
                });

        Page<ReportPageResponse> actual = sut.getReportPage(user, reportPageRequest);

        assertThat(actual.getTotalElements()).isEqualTo(123456L);
        assertThat(actual.getTotalPages()).isEqualTo(1);
        assertThat(actual.getContent()).isEqualTo(reportPageResponses);
    }
}

And my question is I just can verify the mock static object behavior, but can't verify the result, this is my try

pageMockedConstruction = Mockito.mockConstruction(PageImpl.class,
                withSettings().useConstructor(reportPageResponses, pageable, 9999L), (mock, context) -> {
                    when(mock.getTotalElements()).thenReturn(123456L);
                    when(mock.getTotalPages()).thenReturn(1);
                    when(mock.getContent()).thenReturn(reportPageResponses);
                });

        // I thought here will be the same mock object
        // when expected and actual will throught the Mockito.mockConstruction, but actually generate the different object
        PageImpl<ReportPageResponse> expected = new PageImpl<>(this.reportPageResponses, pageable, 9999L);
        Page<ReportPageResponse> actual = sut.getReportPage(user, reportPageRequest);

        // Here will be wrong, because actual and expected has different hashCode
        Assertions.assertThat(actual).isEqualTo(expected);

I research so many articles, but I can't find the answer.

Have somebody encountered the same question?

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

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

发布评论

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

评论(1

抽个烟儿 2025-02-09 03:06:37

powerMock.whennewmockito.mockconstruction之间的主要区别是,mokito在每次构造构建器时实例化时都会创建一个新的模拟打电话。但是powerMock.whennew可以配置为始终返回一个模拟,以构建几个对象。

根据

表示代表类型的任何对象构造的模拟。
在模拟结构的范围内,任何
拦截器将生成一个模拟,该模拟将按照指定准备
生成此范围时。模拟也可以通过此收到
实例。

您可以使用模拟构建&lt; t&gt; .constructed()在上下文中获取所有生成的模拟。它们可用于验证。

检查行为的测试示例:

public class A {
    private final String test;

    public A(String test) {
        this.test = test;
    }

    public String check() {
        return "checked " + this.test;
    }
}

public class TestService {
    public String purchaseProduct(String param) {
        A a = new A(param);
        return a.check();
    }
}

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.MockedConstruction;
import org.mockito.Mockito;

import static org.mockito.Mockito.*;

public class ConstructorMockTest {
    private MockedConstruction<A> mockAController;

    @BeforeEach
    public void beginTest() {
        //create mock controller for all constructors of the given class
        mockAController = Mockito.mockConstruction(A.class,
                (mock, context) -> {
                    //implement initializer for mock. Set return value for object A mock methods
                    //this initializer will be called each time during mock creation 
                    when(mock.check()).thenReturn(" Constructor Mock A ");
                });
    }

    @Test
    public void test() {
        //each instantiation of class A will return new mock, which initialized by initializer from beginTest method
        //new mock will be stored to mockAController.constructed() collection of mocks
        A aObject = new A("test");
        //ensure that method check() returns mocked value
        Assertions.assertEquals(aObject.check(), " Constructor Mock A ");
        //get just created mock for class A from controller. It will be first element of mockAController.constructed() collection
        A aMock = mockAController.constructed().get(0);
        //ensure that we get correct mock from mock controller, that it is equal from new created object
        Assertions.assertEquals(aMock, aObject);
        //verify that check method was executed on Mock
        verify(aMock, times(1)).check();

        //create new A object, new mock created and stored to mockAController.constructed()
        A aObject2 = new A("test");
        //ensure that method check() returns mocked value
        Assertions.assertEquals(aObject2.check(), " Constructor Mock A ");
        //get just created mock for class A from controller, it will be second object from constructed collection
        A aMock2 = mockAController.constructed().get(1);
        //ensure that we get correct mock from mock controller, that it is equal from just created A object
        Assertions.assertEquals(aObject2, aMock2);
        //verify that check method was executed on Mock
        verify(aMock2, times(1)).check();

        //Example of testing service which creates A object
        TestService service = new TestService();
        String serviceResult = service.purchaseProduct("test");
        //ensure that service returned value  from A mock
        Assertions.assertEquals(serviceResult, " Constructor Mock A ");
        //get just created mock for class A from controller, it will be third object from constructed collection
        A aMock3 = mockAController.constructed().get(2);
        //verify that check method was executed on Mock
        verify(aMock3, times(1)).check();
    }

    @AfterEach
    public void endTest() {
        mockAController.close();
    }
}

The main difference between Powermock.whenNew and Mockito.mockConstruction is that Mokito creates a new mock each time when the new object is instantiating when constructor is calling. But Powermock.whenNew can be configured to return one mock always for the construction of several objects.

According to documentation:

Represents a mock of any object construction of the represented type.
Within the scope of the mocked construction, the invocation of any
interceptor will generate a mock which will be prepared as specified
when generating this scope. The mock can also be received via this
instance.

You can use MockedConstruction<T>.constructed() to get all generated mocks in context. They can be used for verification.

Example of test to check behavior:

public class A {
    private final String test;

    public A(String test) {
        this.test = test;
    }

    public String check() {
        return "checked " + this.test;
    }
}

public class TestService {
    public String purchaseProduct(String param) {
        A a = new A(param);
        return a.check();
    }
}

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.MockedConstruction;
import org.mockito.Mockito;

import static org.mockito.Mockito.*;

public class ConstructorMockTest {
    private MockedConstruction<A> mockAController;

    @BeforeEach
    public void beginTest() {
        //create mock controller for all constructors of the given class
        mockAController = Mockito.mockConstruction(A.class,
                (mock, context) -> {
                    //implement initializer for mock. Set return value for object A mock methods
                    //this initializer will be called each time during mock creation 
                    when(mock.check()).thenReturn(" Constructor Mock A ");
                });
    }

    @Test
    public void test() {
        //each instantiation of class A will return new mock, which initialized by initializer from beginTest method
        //new mock will be stored to mockAController.constructed() collection of mocks
        A aObject = new A("test");
        //ensure that method check() returns mocked value
        Assertions.assertEquals(aObject.check(), " Constructor Mock A ");
        //get just created mock for class A from controller. It will be first element of mockAController.constructed() collection
        A aMock = mockAController.constructed().get(0);
        //ensure that we get correct mock from mock controller, that it is equal from new created object
        Assertions.assertEquals(aMock, aObject);
        //verify that check method was executed on Mock
        verify(aMock, times(1)).check();

        //create new A object, new mock created and stored to mockAController.constructed()
        A aObject2 = new A("test");
        //ensure that method check() returns mocked value
        Assertions.assertEquals(aObject2.check(), " Constructor Mock A ");
        //get just created mock for class A from controller, it will be second object from constructed collection
        A aMock2 = mockAController.constructed().get(1);
        //ensure that we get correct mock from mock controller, that it is equal from just created A object
        Assertions.assertEquals(aObject2, aMock2);
        //verify that check method was executed on Mock
        verify(aMock2, times(1)).check();

        //Example of testing service which creates A object
        TestService service = new TestService();
        String serviceResult = service.purchaseProduct("test");
        //ensure that service returned value  from A mock
        Assertions.assertEquals(serviceResult, " Constructor Mock A ");
        //get just created mock for class A from controller, it will be third object from constructed collection
        A aMock3 = mockAController.constructed().get(2);
        //verify that check method was executed on Mock
        verify(aMock3, times(1)).check();
    }

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