自从过去 2 天以来,我试图了解为什么这个简单的测试用例会失败,但无法找到解决方案。
当我运行测试 getAuthors() 它失败了。当我注意到由 mockito 创建的 authorRepo.findAll () 从不调用它时,在 authorservice 内部调用 authorrepo 。正如您在错误中看到的那样,休眠查询是火。
这是我的测试课
@MicronautTest
public class AuthorServiceTest {
@Inject
private AuthorService authorService;
private AuthorRepo authorRepo;
@Test
public void getAuthors(){
authorRepo=Mockito.mock(AuthorRepo.class);
Author a1=new Author(100,"good","morning");
Author a2= new Author(101,"welcome","back");
List<Author>list=new ArrayList<>(); list.add(a1);list.add(a2);
Mockito.when(authorRepo.findAll()).thenReturn(list);
Assertions.assertEquals(2,authorService.getallAuthors().size());
}
}
运行上述测试时产生的错误
10:01:34.846 [Test worker] INFO c.example.service.AuthorServiceImpl - get all Authors
Hibernate:
select
author0_.id as id1_0_,
author0_.first_name as first_na2_0_,
author0_.last_name as last_nam3_0_
from
author author0_
expected: <2> but was: <0>
Expected :2
Actual :0
<Click to see difference>
org.opentest4j.AssertionFailedError: expected: <2> but was: <0>
at org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:55)
at org.junit.jupiter.api.AssertionUtils.failNotEqual(AssertionUtils.java:62)
at org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:150)
at org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:145)
at org.junit.jupiter.api.Assertions.assertEquals(Assertions.java:527)
at com.example.service.AuthorServiceTest.getAuthors(AuthorServiceTest.java:40)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
这是我的服务课
public class AuthorServiceImpl implements AuthorService{
public final AuthorRepo authorRepo;
private static final Logger logger = LoggerFactory.getLogger(AuthorServiceImpl.class);
@Inject
public AuthorServiceImpl(AuthorRepo authorRepo) {
this.authorRepo = authorRepo;
}
@Override
public List<Author> getallAuthors() {
logger.info("get all Authors");
return authorRepo.findAll();
}
}
最后回购
@Repository
public interface AuthorRepo extends CrudRepository<Author,Integer> {
//@Query("SELECT a from Author a where a.book= :isbn")
//public abstract List<Author> findByBook_Isbn(Book isbn);
Author findById(int author_id);
List<Author> findAll();
}