2016-03-18 12 views
1

私はunittestをunittest.mockと一緒に使ってアプリケーションでいくつかのテストをしようとしています。unittest.mockのオブジェクトを二重にする

私はMainClassとCallerという2つのクラスを持っています。二重のCallerでメインクラスをテストしたいと思います。これは私が持っているものに短いです:

私は試験で
class MainClass: 

def __init__(self, caller): 
    self.caller = caller 

def some_function(self): 
    self.caller.function1() 
    blab = self.caller.function2() 

class Caller: 

# some functions non of which should be accessed in tests 


class CallerMock: 
    def __init__(self): 
    self.items = [] 

    def function1(self): 
    pass 

    def function2(self): 
    return items 

class TestMainFunction(unittest.TestCase): 

    def setUp(self): 
     self.mock = MagicMock(wraps=CallerMock()) 
     self.main_class = MainClass(self.mock) 

    def test(self): 
     # self.main_class.caller.items = items 
     # self.mock.items = items 
     # self.mock.function2.return_value = items 
     self.main_class.some_functions() 
     # non of the above change the return value of function2 

問題は、コメント行の非は実際に私の関数2の戻り値を変更することであるが。どうすればこれを達成できますか?

私はdoubleを必要とせず、Callerのすべての関数がNoneを返すソリューションに満足しています。そして、特定のテストで関数の戻り値を指定する必要があります。

答えて

0

Callerを偽装し、call()メソッドにパッチを当てるだけです。そうすれば、ダブルは必要ありません。

def setUp(self): 
    self.mocked_caller = mock.Mock(spec=Caller) 
    self.mocked_caller.call.return_value = items 
    self.main_class = MainClass(self.mocked_caller) 

def test(self): 
    self.main_class.some_function() 
    self.assertTrue(self.mocked_caller.called) 
+0

Mockのすべての機能がMockオブジェクトを返すので、これは解決しません。 run関数が多くの呼び出し側関数を呼び出すように指定する必要があったので、すべての関数のデフォルト戻り値を指定する必要があります – Ela

+0

@Ela次に、使用されているすべての関数に対して 'return_value'を設定できます。 –