dimanche 31 janvier 2021

Is it okay to copy a class method and test its behavior by mocking the class and dependencies in unit tests?

Or I need mock all other methods and dependencies(huge amount) in the class by using @patch, and test through a class call(call method cls.execute() in my service)?

Simple example what I meant:

import unittest
from unittest import mock
from .my_services import MyService

class MyServiceTestCase(unittest.TestCase):

    def test_set_name(self):
        mocked_service = mock.Mock()
        mocked_service._names = ["Arnold", "Ken", "Alex"]
        mocked_service.exact_name = ""

        set_last_name = MyService.set_last_name
        set_last_name(mocked_service)

        self.assertEqual(mocked_service.exact_name, "Alex")

Imagine that to get the ._names you'll need to call five other methods by making calls to the database and api.

I'm new to testing. So copying the method and testing it separately, checking the desired changes in the mocked class seems like a good idea to me. But is it really so?

Aucun commentaire:

Enregistrer un commentaire