我正在尝试 UT 我的小项目,但遇到了问题。
我的应用程序使用简单的分层架构,我不能碰巧UT服务层。
事实上我想嘲笑班级Crud存储库 https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/CrudRepository.html来自 Spring 数据。
我正在尝试模拟我的存储库之一的 findAll 方法,该方法扩展了此类,但mockito无法模拟接口。
除了自己创建豆子并填充它之外,还有其他方法可以简单地做到这一点吗?
[更新]
这是存储库代码:
package fr.kaf.interview.Repository;
import fr.kaf.interview.model.Book;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface BookRepository extends CrudRepository<Book,Long> {
}
这是UT:
@ExtendWith(MockitoExtension.class)
class BookServiceTest {
@Mock
private BookRepository bookRepository;
@InjectMocks
private BookService bookService;
@Test
public void should_get_All_books_from_database() {
//Given
Person author = new Person();
author.setFirstName("Ka");
author.setLastName("AwQl");
Book firstBook = new Book();
firstBook.setTitle("One Book");
firstBook.setAuthors(singletonList(author));
Book secondBook = new Book();
secondBook.setTitle("Second Book");
secondBook.setAuthors(singletonList(author));
given(bookRepository.findAll()).willReturn(asList(firstBook, secondBook));
//When
List<Book> allBooks = bookService.getAllBooks();
//Then
assertThat(allBooks).containsExactly(firstBook, secondBook);
}
}
我想知道问题是否在于 Mockito 不确定如何注入bookService
进入 Spring TestContext。
我会尝试用注释来注释测试@ExtendWith(SpringExtension.class)
正如“底部的建议”编写测试依赖注入 https://junit.org/junit5/docs/current/user-guide/#writing-tests-dependency-injectionJUnit5 用户指南的“部分。
该注释的源代码是here https://github.com/spring-projects/spring-framework/blob/master/spring-test/src/main/java/org/springframework/test/context/junit/jupiter/SpringExtension.java.
我也认为有可能given
Mockito 的 BDD 风格 https://static.javadoc.io/org.mockito/mockito-core/2.24.0/org/mockito/Mockito.html#bdd_mockito和when\\then
风格可能会产生不同的结果。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)