SaiyanGirl
SaiyanGirl

Reputation: 17034

How to give default return value to a method that is called during a unit test? - Python

Here's an example class that simplifies what I have:

class.py

class MyClass(object):

    @staticmethod
    def getDictionary():
        #some calculations, returns a dictionary 

    def checkConfiguration(self):
        #some code
        self.getDictionary()
        #some other code
        return value

And now I am making a unit test for checkConfiguration:

classTest.py

import class
import unittest

class TestMyClass(unittest.TestCase):

    def setUp(self):
        self.classTest = class.MyClass() 

    def test_CheckConfiguration(self):
        #What to put here?

The original CheckConfiguration calls getDictionary. Is there a way to tell the test_CheckConfiguration(self) that if getDictionary is called, it should automatically return a dictionary I can type in? Something like:

    def test_CheckConfiguration(self):
        if method getDictionary is called: 
            return {'a':123, 'b':22}
        checkValue = self.classTest.checkConfiguration()

I know this is possible in Java, though I don't have enough experience in that nor this. Thank you.

Upvotes: 4

Views: 220

Answers (2)

Sam Mussmann
Sam Mussmann

Reputation: 5993

I think you need a mocking framework. I suggest PyMock.

Here's how you could use it:

classTest.py

import class
import pymock
import unittest

class TestMyClass(pymock.PyMockTestCase):

    def setUp(self):
        self.classTest = class.MyClass() 

    def test_CheckConfiguration(self):
        self.override(self.classTest, 'getDictionary')
        pymock.expectAndReturn(self.classTest.getDictionary(), {'a':123, 'b':22})
        self.replay()
        checkValue = self.classTest.checkConfiguration()
        self.verify()

Upvotes: 2

Silas Ray
Silas Ray

Reputation: 26160

https://groups.google.com/forum/?fromgroups#!topic/comp.lang.python/WBhc1xAc8Hw suggests subclassing your class under test and overriding __getattribute__ to record each call in whatever manner you need. Not sure what else would work...

Upvotes: 1

Related Questions