How to write golang integration test with MySQL

huangapple go评论83阅读模式
英文:

How to write golang integration test with MySQL

问题

我想编写一个使用MySQL来测试查询的集成测试。在golang中如何做到这一点?

这里有几个问题:

  1. 如何在golang测试中设置MySQL(内存中的)服务器?
  2. 如何在每个测试之前/之后清除/重新创建数据模型,以确保它们不会留下垃圾?
  3. 在所有测试完成后如何拆除MySQL?
英文:

I want to write an integration test that uses MySQL to test my queries. How to do this in golang?

This contains few questions:

  1. How to setup MySQL (in-memory?) server in golang test?
  2. How to clean/recreate data model before/after each test so that they do not leave garbage behind?
  3. How to tear down mysql after all the tests are done?

答案1

得分: 5

如果你真的想要嵌入MySQL,你可以使用golang的C绑定来集成:https://dev.mysql.com/doc/refman/5.1/en/libmysqld.html。我还没有看到任何将这些绑定封装成一个好的Go包的项目,这将是一个有趣的小项目。

否则,你可以使用Docker来设置一个一次性的MySQL服务器,但在运行go test之前,需要进行一些设置/拆除步骤。这就是我们在我工作的地方所做的。

在这两种情况下,你都需要编写设置/拆除方法,根据需要创建和删除表。这些只是普通的SQL语句,如DROP DATABASE、CREATE TABLE等。

Testify https://github.com/stretchr/testify 提供了设置/拆除的工具,但只编写一个辅助函数也可以正常工作。

英文:

If you really want to have an embedded MySQL, you can use golangs C bindings to integrate with: https://dev.mysql.com/doc/refman/5.1/en/libmysqld.html. I haven't seen any project packing up the bindings for this in a nice Go package, that would be an interesting small project.

Otherwise you can use Docker to set up a throwaway MySQL server, this requires some setup/teardown steps before you run go test though. This is what we are doing where I work.

In both cases, you will need to write setup/teardown methods that creates and drops tables as needed for your tests. These are just normal SQL statements, DROP DATABASE, CREATE TABLE etc.

Testify https://github.com/stretchr/testify has tooling for setup/teardown, but just writing a helper function for this works just fine.

huangapple
  • 本文由 发表于 2015年4月28日 13:11:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/29910793.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定