尝试模拟存储库中的findById
方法,但是不知道使用thenReturn()
返回对象,因为它接受Optional
吗?
PS在Spring Boot 2环境中测试
import static org.mockito.Mockito.*;
import org.springframework.boot.test.mock.mockito.MockBean;
@MockBean
private BookRepository mockRepository;
@Before
public void init() {
Book book = new Book(1L, "A Book");
//error, can't resolve method thenReturn(book)?
when(mockRepository.findById(1L)).thenReturn(book);
}
解
尝试Optional.of()
@MockBean
private BookRepository mockRepository;
@Before
public void init() {
Book book = new Book(1L, "A Book");
when(mockRepository.findById(1L)).thenReturn(Optional.of(book));
}
参考文献
翻译自: https://mkyong.com/spring-boot/mockito-how-to-mock-repository-findbyid-thenreturn-optional/