我正在努力进行集成测试编写,我想测试与JPA存储库通信的服务,但由于测试无法运行并在我的服务上抛出NPE,我似乎犯了一个错误。
我的应用程序运行在springboot配置上(没有奇怪的依赖关系,我想尽可能多地保留库存以避免副作用)。
我的服务管理用户,确实很简单: -自动连接的存储库 -一种调用存储库的方法(我想在添加控制逻辑之前先进行测试)
@Service
public class ApplicationUserService{
@Autowired
private ApplicationUserRepository applicationUserRepository;
public ApplicationUser getUserByFirstname(String firstnameToLookFor){
return this.applicationUserRepository.findByFirstname (
firstnameToLookFor );
}
}
存储库也很简单:
public interface ApplicationUserRepository extends
JpaRepository<ApplicationUser, Integer> {
// ...
ApplicationUser findByFirstname(String firstname);
}
最后我的测试与其他两个元素一样非常简单:
@RunWith (SpringRunner.class)
public class UserServiceIntegrationTest {
@TestConfiguration
static class UserServiceTestContextConfiguration {
@Bean
public ApplicationUserService applicationUserService(){
return new ApplicationUserService ();
}
}
@Autowired
private ApplicationUserService applicationUserService;
@MockBean
private ApplicationUserRepository applicationUserRepository;
@Before
public void setup(){
ApplicationUser user = new ApplicationUser ("darky", "bruce@wayne.com",
"iLoveSelin4", "Bruce", "WAYNE", "en");
Mockito.when (applicationUserRepository.findByFirstname (
user.getUsername () )).thenReturn ( user );
}
@Test
public void getUserByFirstName() {
String firstnameToLook = "Bruce";
ApplicationUser userFound = applicationUserService.getUserByFirstname (
firstnameToLook );
assertThat(userFound.getFirstname ()).isEqualTo ( firstnameToLook );
}
}
据说,测试必须可以。
但是正如前面所说,我在断言assertThat(userFound.getFirstname ()).isEqualTo ( firstnameToLook );
上抛出了NPE,并且当我在断言之上的那一行调试时,我可以看到applicationUserService
为空。
我在这里做什么错了?
感谢您的帮助!