Quantcast
Channel: What's the difference between a mock & stub? - Stack Overflow
Viewing all articles
Browse latest Browse all 43

Answer by radtek for What's the difference between a mock & stub?

$
0
0

I have used python examples in my answer to illustrate the differences.

Stub - Stubbing is a software development technique used to implement methods of classes early in the development life-cycle. They are used commonly as placeholders for implementation of a known interface, where the interface is finalized or known but the implementation is not yet known or finalized. You begin with stubs, which simply means that you only write the definition of a function down and leave the actual code for later. The advantage is that you won't forget methods and you can continue to think about your design while seeing it in code. You can also have your stub return a static response so that the response can be used by other parts of your code immediately. Stub objects provide a valid response, but it's static no matter what input you pass in, you'll always get the same response:

class Foo(object):    def bar1(self):        pass    def bar2(self):        #or ...        raise NotImplementedError    def bar3(self):        #or return dummy data        return "Dummy Data"

Mock objects are used in mock test cases they validate that certain methods are called on those objects. Mock objects are simulated objects that mimic the behaviour of real objects in controlled ways. You typically creates a mock object to test the behaviour of some other object. Mocks let us simulate resources that are either unavailable or too unwieldy for unit testing.

mymodule.py:

import osimport os.pathdef rm(filename):    if os.path.isfile(filename):        os.remove(filename)

test.py:

from mymodule import rmimport mockimport unittestclass RmTestCase(unittest.TestCase):    @mock.patch('mymodule.os')    def test_rm(self, mock_os):        rm("any path")        # test that rm called os.remove with the right parameters        mock_os.remove.assert_called_with("any path")if __name__ == '__main__':    unittest.main()

This is a very basic example that just runs rm and asserts the parameter it was called with. You can use mock with objects not just functions as shown here, and you can also return a value so a mock object can be used to replace a stub for testing.

More on unittest.mock, note in python 2.x mock is not included in unittest but is a downloadable module that can be downloaded via pip (pip install mock).

I have also read "The Art of Unit Testing" by Roy Osherove and I think it would be great if a similar book was written using Python and Python examples. If anyone knows of such a book please do share. Cheers :)


Viewing all articles
Browse latest Browse all 43

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>