Skip to content Skip to sidebar Skip to footer

How To Permanently Mock Return Value Of A Function In Python Unittest

I have a function # foo.py NUM_SHARDS = 10 def get_shard(shard_key: int) -> int return (shard_key % NUM_SHARDS) + 1 I want to mock this function such that whenever this fun

Solution 1:

The mock.patch method is meant to temporarily mock a given object. If you want to permanently alter the return value of a function, you can simply override it by assigning to it with a Mock object with return_value specified:

import foo
from unittest.mock import Mock
foo.get_shard = Mock(return_value=11)

Post a Comment for "How To Permanently Mock Return Value Of A Function In Python Unittest"