[Grok-dev] How does one unittest a view?

Wichert Akkerman wichert at wiggy.net
Wed Apr 8 10:26:06 EDT 2009

Previously Santiago Videla wrote:
> Hi Wichert,
> I don't understand why you would unittest a View. Could you give some
> examples of use case? I do understand the idea of `test things in isolation`
> but I don't understand what `things in a view` would you like to `test in
> isolation`

I have a number of methods in my View which collect and modify some
data, which can then by used by the template. I am trying to unit test
these methods. For example here are two test I have:

    def testProfileQuestions_ReturnedData(self):
        view=View(model, self._request())
        child=Mock(id="child", title=u"Child")
        alsoProvides(child, IProfileQuestion)
        self.assertEqual(pq[0], dict(id="child",

    def testProfileQuestions_OtherChild(self):
        view=View(model, self._request())
        child=Mock(id="child", title=u"Child")
        self.assertEqual(len(pq), 0)

as you can see the tests are simple: I create a model instead,
instantiate a view, call the ProfileQuestions method on it and check if
the results are correct.

> I mean, if you have some methods in a View, but this methods doesn't need
> the request instance at all (that seems from the tests examples you posted),
> why don't write that methods in the Model or in some Utility and write
> unittest for those

These methods are only useful for preparing data to be used by the view.
They do not make sense in any other context, so putting the View class
is a logical place to put them.


Wichert Akkerman <wichert at wiggy.net>    It is simple to make things.
http://www.wiggy.net/                   It is hard to make things simple.

More information about the Grok-dev mailing list