djangounit-testingtestingunittest2

What's a good practice when unittesting views that perform calls to external services in django


We have this view that look something like this:

from fblib import Facebook

def foo(request):
    fb = Facebook( settings.facebook )
    data = fb.get_thingy()
    return render_to_response( .. , data, .. )

What would be a good way of testing that? Since the view fetches the resource by itself I'm unsure how I could mock Facebook. One alternative in my mind is to create a fake Facebook server and supply the connection details in the settings. So we get a unittest that look something like this:

from fakebook import FakeFacebookServer

class ViewsFooTests(TestCase):
    def set_up( self ):
        self.facebook = FakeFacebookServer().start()

    def test_foo_connect( self ):
        response = self.client.get('/foo')
        self.assertEquals( response.status_code, 200 )

The issue I have with the that is that it seem like making a fake Facebook server seem like a lot of hassle. Ideally I would rather be able to mock the Facebook.get_thingy method. Suggestions?


Solution

  • You can modify your views module from your tests for mocking your library:

    # tests.py
    import myapp.views
    ...
    
        def setUp(self):
            myapp.views.Facebook = FaceBookMock