gpt4 book ai didi

java - @MockBean 返回空对象

转载 作者:行者123 更新时间:2023-12-05 02:40:10 30 4
gpt4 key购买 nike

我正在尝试使用@MockBean; java 版本 11、Spring Framework 版本 (5.3.8)、Spring Boot 版本 (2.5.1) 和 Junit Jupiter (5.7.2)。

    @SpringBootTest
public class PostEventHandlerTest {
@MockBean
private AttachmentService attachmentService;

@Test
public void handlePostBeforeCreateTest() throws Exception {
Post post = new Post("First Post", "Post Added", null, null, "", "");

Mockito.when(attachmentService.storeFile("abc.txt", "")).thenReturn(new Attachment());

PostEventHandler postEventHandler = new PostEventHandler();
postEventHandler.handlePostBeforeCreate(post);
verify(attachmentService, times(1)).storeFile("abc.txt", "");
}
}
    @Slf4j
@Component
@Configuration
@RepositoryEventHandler
public class PostEventHandler {
@Autowired
private AttachmentService attachmentService;

@Autowired
private PostRepository postRepository;

public void handlePostBeforeCreate(Post post) throws Exception {
...
/* Here attachmentService is found null when we execute above test*/
attachmentService.storeFile(fileName, content);
...
}
}

attachmentService 没有被模拟它返回 null

最佳答案

我认为你误解了 Mocks 的用法。

@MockBean 确实创建了一个模拟(内部使用 Mockito)并将这个 bean 放到应用程序上下文中,以便它可用于注入(inject)等。

但是,作为程序员,您有责任指定当您在其上调用一种或另一种方法时,您期望从该模拟返回什么。

因此,假设您的 AttachementService 有一个方法 String foo(int):

public interface AttachementService { // or class 
public String foo(int i);
}

您应该在 Mockito API 的帮助下指定期望:

    @Test
public void handlePostBeforeCreateTest() throws Exception {
// note this line, its crucial
Mockito.when(attachmentService.foo(123)).thenReturn("Hello");

Post post = new Post("First Post", "Post Added", null, null, "", "");
PostEventHandler postEventHandler = new PostEventHandler();
postEventHandler.handlePostBeforeCreate(post);
verify(attachmentService, times(1)).storeFile("", null);
}

如果您不指定期望,并且如果您的被测代码在某个时候调用了 foo,则此方法调用将返回 null

关于java - @MockBean 返回空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68707300/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com