如何使用 Spock 与 neo4j spring data rest 和 Neo4jRepository 进行集成测试

问题描述

这是我尝试使用测试容器运行的测试

@Testcontainers
class UserIntTest extends Specification {

   @Autowired
   private UserDao userDao

   @Shared
   private static Neo4jContainer neo4jContainer = new Neo4jContainer()
           .withAdminPassword(null); // Disable password


   def "sample test integration user test"() {
      given: " a user to persist"
      String email = "test@test.com"
      String username = "Test"
      String password = "encrypted"
      String firstName = "John"
      String lastName = "Doe"
      User user = createUser(email,username,password,firstName,lastName,null)

      when: "I persist the user"
      def userdb = userDao.save(user)
      
      then:
      userdb.getEmail() == email
   }
}

但是当我运行测试时出现以下错误:

java.lang.NullPointerException: Cannot invoke method save() on null object

    at com.capstone.moneytree.controller.UserIntTest.sample test integration user test(UserIntTest.groovy:37)


Process finished with exit code 255

据我了解,这是因为 UserDao 未初始化。我的 userDao 看起来像这样:

@Repository
public interface UserDao extends Neo4jRepository<User,Long> {

    List<User> findAll();

    User findUserById(Long id);

    User findUserByEmailAndUsername(String email,String username);

    User findUserByEmail(String email);
}

知道如何让它发挥作用吗?

解决方法

正如评论中所建议的,您需要配置 Spring 测试运行器,以便通常的 Spring 注释(例如 @Autowired)启动并且应用程序上下文加载您的存储库 bean。

幸运的是,只需使用 @SpringBootTest@DataNeo4jTest 注释您的测试类就足够了,因为这些注释也包括测试运行程序注释。

注意:您应该选择最具体的测试注释(如果您只测试您的存储库,@DataNeo4jTest 就足够了)。

特别是对于 Spock,您还需要提取 spock-spring 依赖项,如文档 here 所述。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...