0

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

@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);
}

关于如何使它工作的任何想法?

4

1 回答 1

1

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

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

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

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

于 2021-01-11T12:13:53.600 回答