For example, You have a function called Router that takes a DB struct.
The DB struct has a field called mdb which is a connection to monogdb database.
A function called InitDB opens a mongdb connection and returns *DB. Then, You can use this value returned by InitDB to call Router.
All looks good, Right??
well, Now, What if you want to write tests for your code?
If you continue with current approach, It means, You'll need a environment where you can run the database, Seed some initial values in database and maybe even reset them after every test.
This quickly becomes a PITA.
What if Router took a interface called IDB. This interface has definitions of all the methods that you'll use in rest of your code.
When you want to run you code in production, The DB struct implements IDB Interface and DB struct can be passed to Router because router takes IDB.
When you want to test your code, You create another struct called FDB that also implements IDB Interface, But instead of establishing connection with a database and everything, It only mocks the database.
For example,
When you store a json blob in database, The database responds with { result: "ok" }, In the method defined on DB struct, it goes ahead and stores the value in database and sends whatever response database sent back.
But in the method defined on FDB, You don't call the database routines at all, You just mock the database response and send it back.
Thanks, this clears things a bit ^_^
This was a great explanation of interfaces and an example of how to implement them. It should help me with the issue I posted above, thanks for this. At least it gives me a direction to go in.
Обсуждают сегодня