Relevance of MockedEntity in unit test

Hello everyone,

Please see below an example of a unit test.

What is the relevance of “entities={1: MockedEntity(entity_type=“my_mocked_entity”)}”?

What can I do with it that can’t be done without this line?

# 1 - Imports from app
# 1.1 - Import the class Controller to be tested
# 1.2 - Import the function to be tested (if outside Controller)

# 2. Imports from libraries/viktor
import unittest
from viktor.testing import (
    MockedEntity,
    mock_params,
    mock_View,
)


class TestController(unittest.TestCase):

    def test_myfunc(self):

        # A nested dict with steps and parameters
        params_args = {
            "my_step": {
                "param_1": 1,
                "param_2": 'some value',
            }
        }

        # Mock the parametrization
        mocked_params = mock_params(
            params=params_args, # the nested dict
            parametrization=Controller.parametrization(), # a parametrization instance, don't forget ()
            entities={1: MockedEntity(entity_type="my_mocked_entity")} # if not relevant, delete this line
            )

        # Here get result returns a numerical value, as an example case
        result = get_result(params=mocked_params)

        self.assertEqual(result, 1.0)

Hi Kassi,

In the example that you present, where you simply pass a dictionary with your params to a function that you wrote yourself, the MockedEntity is not necessary indeed.

Mocking is used as you need to run your tests in controlled environment, independent of outages of services for instance:

  • You do not want to spend time figuring out a problem with your code only to realise that your internet connexion is failing
  • You do not want to continuously run a misconfigured worker only to test if your code raises that correct error message in that case

This means that will need to mock API calls for instance, there are no other entities in the online database, you “fake” those.

In this context, the MockedEntity is used as a ‘replacement’ of the of the Entity object that can be returned by the API or an EntityOptionField. If you are not using the API and any objects of type Entity in your code, for instance to access the params of a parent entity, you do not need to use the MockedEntity Object.

More information about

I hope this helps!

kind regards,
Paulien