close

How to supply a mock class method for python unit test?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to supply a mock class method for python unit test in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to supply a mock class method for python unit test?

  1. How to supply a mock class method for python unit test?

    Since you want to mock out the method with a custom implementation, you could just create a custom mock method object and swap out the original method at testing runtime.

  2. supply a mock class method for python unit test

    Since you want to mock out the method with a custom implementation, you could just create a custom mock method object and swap out the original method at testing runtime.

Method 1

Here is a simple way to do it using mock

import mock


def new_loaddata(cls, *args, **kwargs):
    # Your custom testing override
    return 1


def test_SomeProductionProcess():
    with mock.patch.object(SomeProductionProcess, 'loaddata', new=new_loaddata):
        obj = SomeProductionProcess()
        obj.loaddata()  # This will call your mock method

I’d recommend using pytest instead of the unittest module if you’re able. It makes your test code a lot cleaner and reduces a lot of the boilerplate you get with unittest.TestCase-style tests.

Method 2

To easily mock out a class method with a structured return_value, can use unittest.mock.Mock.

from unittest.mock import Mock

mockObject = SomeProductionProcess
mockObject.loaddata = Mock(return_value=True)

EDIT:

Since you want to mock out the method with a custom implementation, you could just create a custom mock method object and swap out the original method at testing runtime.

def custom_method(*args, **kwargs):
    # do custom implementation

SomeProductionProcess.loaddata = custom_method

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read