Razine Bensari
Razine Bensari

Reputation: 31

How to make integration test with neo4j spring data rest and Neo4jRepository using Spock

Here is the test I am trying to run using test containers

@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 = "[email protected]"
      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
   }
}

But when I run the test I have the following error:

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

Which, from my understandnig, it is because the UserDao is not initialized. My userDao looks like that:

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

any idea on how to make it work?

Upvotes: 0

Views: 379

Answers (1)

fbiville
fbiville

Reputation: 8970

As suggested in the comments, you need to configure the Spring test runner, so that the usual Spring annotations (such as @Autowired) kick in and the application context loads with your repository beans.

Fortunately, just annotating your test class with @SpringBootTest or @DataNeo4jTest is enough, as those annotations include the test runner annotation as well.

Note: you should pick the most specific test annotation (if you test only your repositories, @DataNeo4jTest is enough).

Specifically for Spock, you also need to pull the spock-spring dependency, as documented here.

Upvotes: 1

Related Questions