![](/img/trans.png)
[英]How to check that a method is not being called using JUnit Mockito Verify
[英]How to define the behavior of a method that is called by chain dependency using Mockito and JUnit?
如何在鏈依賴項調用方法的地方模擬這種方法調用?
happyPostsDto.setImage(post.getUser().getImage().getImageUrl());
到目前為止,我已經嘗試過了,但是沒有解決。
@Mock
HappyPost happyPost;
@Mock
User user;
@Mock
Images images;
並在@Test方法中
when(happyPost.getUser()).thenReturn(new User());
when(user.getImage()).thenReturn(new Images());
when(images.getImageUrl()).thenReturn("jhv");
Assertions.assertEquals(happyPosts.size(),happyPostService.mapHappyPosts(happyPosts).size());
請幫幫我。
您需要建立自己的模擬對象鏈。 我發現您正在嘗試返回new User()
和new Images()
。 代替這些,創建自己的mockedUser
和mockedImages
。 您可以執行以下操作:
...
// create mocked objects of user and images
User mockedUser = Mockito.mock(User.class);
Images mockedImages = Mockito.mock(Images.class);
//now create a chain
when(mockedImages.getImageUrl()).thenReturn("jhv");
when(mockedUser.getImage()).thenReturn(mockedImages);
when(happyPost.getUser()).thenReturn(mockedUser);
...
附帶說明:您已經在嘲笑這些:
@Mock
User user;
@Mock
Images images;
因此,您也可以使用user
來代替mockedUser
。 images
和mockedImages
images
也是mockedImages
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.