如何解决如何使用 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 所述。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。