I am currently figuring out a way to mock the dgraph client so that I can write my unit test case in Golang. The Dgraph client is being written without interfaces which make it impossible to mock for custom behaviour.
I know i can spin up the container and connect to it and test it out, but thats not what unit tests are. it should be run independently without any dependecies. I want to know if I am missing something or its how the Dgraph client has been written? Can someone please help me out here to understand.
I wouldn’t mock out dgo client. Instead, I’d do this rails style. Open a transaction at the start of the test, do a bunch of things with dgo, assert on the transaction output, then rollback everything at the end of the test.
You could use mock to mock Dgraph client, but since there is no interface defined, that might be a bit tough.
Instead I would create an interface DgraphClient { Dgraph *actualClient } in my app, and make domain specific functions like func (self *DgraphClient) GetAllCustomers() or something like that. Then you can use go mock to mock it out. https://github.com/golang/mock
Not sure what you mean open a transaction. I will not be able to open a transaction since there is no real dgraph connection. Just to be clear, i am interested in unit tests, not integration test.
I dont think its currently possible to mock the dgraph client. can you please provide an example may be using mock library to mock the client.
yes thats one of the solution i am thinking about. but the way our code is structured (its a bit messy), it will require lot of refactoring. So wanted to avoid if possible.
Yes you are right @Ohm_Patel. It’s tough to mock out Dgraph since there is no interface.
I come from a Ruby on rails background so what I call a “unit” test, you call an integration test (ie, it actually makes the calls to the db). In my experience (using Dgraph to build products within Dgraph labs) testing within a transaction is easy and fast.
Open a transaction at the start of the test, do a bunch of writes in transaction, do a bunch of reads and assert on stuff, dump the transaction at the end.
In my head these are still “unit tests” as you aren’t really testing the integration between systems, it’s still a unit of code (again; this is likely due to my rails heritage in which this is the norm).
FWIW: Dgraph cloud was mostly built with TDD using the above approach.
It creates a transient dgraph cluster within the address space of your Go test. I wrote it to be able to run integration tests without having to manage dgraph docker containers on my machine. Also used it effectively in CI.
Thanks Matthew, but this is again an integration test solution, since you are spinning a docker container rather programatically, and testing out against.