0

Completely new to Python unit testing. A bit of code.

class a():
    def __init__(param1, param2)
    self.param1 = param1
    self.param2 = param2
    self._problem = SomeOtherClass()

    def method1(self):
        self._problem.some_method()

    def method2(self):
        self._problem.some_other_method()

    def problem(self):
        return self._problem

Now , I am writing unit tests for class a. For testing the init, method1 and method2, I somehow need to mock the instance of SomeOtherClass along with its 2 methods that has been called. Now I though of using a fixture as:

@pytest.fixture
def problem():
    pro = mock.MagicMock()
    pro.some_method = mock.MagicMock()
    pro.some_other_metho = mock.MagicMock() 

Now the test :

def test_init_success(problem):
    a_instance = a(12, 13)
    assert a_instance.problem == problem

The other option I have is to use a patch. Which one should I use?

EDIT1 : The assertion in test_init_will fail as problem was not passed as param for the init method. Is there any workaround for this ?

amrx
  • 673
  • 1
  • 9
  • 23
  • I don't understand your **edit1** section... Can you review it and make it more clear by an example of what fail and how? – Michele d'Amico Mar 19 '15 at 11:29
  • Is it impossible to answer your question if you don't make it more clear in the last part. If you don't want spend more effort on it pleas close the question. – Michele d'Amico Mar 21 '15 at 13:59
  • Sorry about that, weekend :) , I made the edit after I tried the test . What I meant in the edit is that even though I have a fixture 'problem' which does mocks the behaviour of some class , but since that instance of class was not passed as a parameter to the init of class a , the assertion fails – amrx Mar 23 '15 at 05:45
  • Yes, you have some issues in your tests. I'll try to cook an answer later in the day (I'm little bit busy).... In the meantime take a look to [Monkeypatching/mocking modules and environments](https://pytest.org/latest/monkeypatch.html#monkeypatching-mocking-modules-and-environments). I think here you can find the answer to your patching issue – Michele d'Amico Mar 23 '15 at 07:24
  • Nailed it with patch :) – amrx Mar 26 '15 at 07:38

0 Answers0