DATA-DOG / go-sqlmock

Sql mock driver for golang to test database interactions
Other
6.05k stars 406 forks source link

how to create table use go-sqlmock #219

Open jigetage opened 4 years ago

jigetage commented 4 years ago

is it possible to create a mysql database in memory use go-sqlmock? just like https://github.com/alicebob/miniredis which creates a redis server in your own computer's memory with golang. if so, we can use the mocked mysql instead of the real mysql server, i think it will be the ultimate solution for mysql mock in golang.

l3pp4rd commented 4 years ago

sqlmock is used for testing purposes, not for in memory db. you can still implement your functional tests very efficiently by using sqlite (if you just use SQL standard queries) or by using https://github.com/DATA-DOG/go-txdb which would wrap your mysql or other SQL database within a transaction, reverting transaction is instant and so your tests would be fast without any need to change your actual code.

Sqlmock is not validating sql statements and does not have an in memory query processing engine. SQL databases are different, they have different query engines and in some cases sql syntax additions. Sqlmock will never even try to implement an SQL query engine. Additionally, every database handles indexes or primary key generation differently, default ordering of records created and so on. It would be insane to even try to do such a thing.

danielkurniadi commented 4 years ago

@l3pp4rd Perhaps relevant and not sure if this is the same question. Basically I wonder if there is a way to pre-populate the "Mock database" with some rows. I have seen the following for testing Query get:

ExpectQuery(...).WillReturnRows(...)

But I'm testing for failed insert when inserting row with duplicate unique email or username. Is there a way to do it in sqlmock? thanks!

l3pp4rd commented 4 years ago

As I said, sqlmock is meant for unit testing certain functions or blocks of logic. It would not be wise to use it for functional tests and try to test the logic in the database you use, because it cannot replicate a database it can only mock one for an unit test.

It would be much wiser to use a real database to functionally test your code. Especially the internal database behavior, such as duplicate key failures.

If you mock the database, how you can think that your test is testing anything at all what is happening in db, such as duplicate unique key or any other constraints or locks or ordering behavior.

Sqlmock only helps to test you the correct program flow in certain conditions which you simulate. But it will not give you functional behavior tests

danielkurniadi commented 4 years ago

I understand now. Thank you.