如何使用 postgres 在本地和构建服务器上进行单元测试?

How to make unit tests on local and on build server using postgres?

我正在尝试为我的节点应用程序进行单元测试。我使用 postgresql 数据库进行开发,使用 SQLite 进行测试。然而,Sqlite 不理解 postgresql 的某些功能,例如 to_tsvector,有时我会遇到 SQLITE databse locked 的问题。所以我认为服务器可以在本地和构建服务器上测试应用程序。这是一个很好的解决方案吗?我找到了一些提到使用 docker container 的替代方法 testing with docker.

那么 运行 在本地和服务器构建上进行 postgres 测试而不会出现数据库锁定问题的合适解决方案是什么?

I would avoid using the database in the unit tests as they are now dependant on an external system:

Part of being a unit test is the implication that things outside the code under test are mocked or stubbed out. Unit tests shouldn't have dependencies on outside systems. They test internal consistency as opposed to proving that they play nicely with some outside system.

基本上,模拟对数据库的任何调用,这样您就不需要使用它们了。

但是,如果您确实必须使用 Postgres 数据库,则应在撰写文件中使用 official image 并使用您的架构对其进行初始化。然后,您可以使用已知状态的测试连接到它,等等。

至于数据库锁,它可能会在使用 Postgres 而不是 SQLite 后消失,您可能需要检查您的测试中是否有任何并发​​。