vendredi 15 novembre 2019

Unit tests design & mocking

Say I have the following class and i want to test it.

class SearchRecommended:
    def __init__(self, request2template):
        self._r2t = request2template

    def handle(self, request: Request):
        return request.user().queries().add_recommendation_query().run(1).print(
            RecommendedSearchMedia(self._r2t(request))
        ).message(RecommendedSearchMessage)

The object returned by .user() belongs to the User "interface" and is database-related.

class User(Equalable, ABC):
    @abstractmethod
    def user_id(self):
        pass

    @abstractmethod
    def lang(self):
        pass

    @abstractmethod
    def queries(self) -> "UserQueries":
        pass

    @abstractmethod
    def subscriptions(self) -> "UserSubscriptions":
        pass

    @abstractmethod
    def notifications(self) -> "UserSubsNotifications":
        pass

    @abstractmethod
    def access(self) -> "UserAccess":
        pass

    def repr(self):
        return self.user_id()

UserQueries, UserSubscriptions, UserSubsNotifications, UserAccess are also base classes for database-interacting classes.

As far as I know, unit-tests are meant to be fast and shouldn't use the actual database connection. Unit tests also shouldn't know too much about the inner structure of the code they are testing.

Mocking the whole database interaction layer is tedious, but mocking only methods used in the method being tested seems like "knowing too much" about the inner code.

Am I getting something wrong & what should I do?

Aucun commentaire:

Enregistrer un commentaire