Just to get any confusion out of the way: I'm starting from the position where I already know what to mock, where and how to do it. I just don't know how to fit the mocking into the TDD process.
So let's say I have a my_function() already done and I want to write MyClass() that uses my_function() somewhere. Let's say my end goal is something like this:
class MyClass():
(...)
def some_method():
var = my_function()
self._do_something(var)
Writing this the classical way would be easy:
- Write the code.
- Realize that my_function() needs to be mocked because it does some connections and stuff.
- Write a my_function mock.
- Write a test for MyClass().some_method() using the mock.
- Run the test.
I want to do it test first though, but so far I've only came up with this:
- Write the test for MyClass().some_method(), ignoring the mock.
- Run the test - it fails.
- Write the code.
- Run the test - it fails because my_function() has some external dependencies and needs a certain environment etc.
- Write the mock and change the test.
- Run the test - it passes.
This approach seems flawed though. I write the test first so I can just run it again and again while writing code, waiting for it to go green. With my approach my test will never go green before I decide that I'm "done" with the code and only then start mocking (because I won't know what to mock before writing the code). Also I'm actually changing the test so it uses the mock, while the code is already "done" so I'm running the test to actually check whether I'm done changing the test, and not changing the code (I hope I'm making sense here).
What do you make of it? Is my TDD process flawed or is it ok and my reasoning about it is flawed? I tried searching the net but I haven't found anyone discussing or explaining this particular aspect. Either it's just mocking, assuming the code is already written, or it's TDD and the assumption is that you don't have any dependencies to mock.