Python在特定参数时模拟方法

时间:2019-10-23 10:11:12

标签: python mocking

我有一个类似python的方法

import external_object

from external_lib1 import ExternalClass1
from external_lib2 import Hook

class MyClass(self):

    def my_method(self):
        ExternalClass.get('arg1') #should be mocked and return a specific value with this arg1
        ExternalClass.get('arg2') #should be mocked and return a specific value with this arg2

    def get_hook(self):
        return Hook() # return a mock object with mocked method on it

    def my_method(self):
        object_1 = external_object.instance_type_1('args') # those are two different object instanciate from the same lib.
        object_2 = external_object.instance_type_2('args')

        object_1.method_1('arg') # should return what I want when object_1 mocked
        object_2.method_2 ('arg') # should return what I want when object_2 mocked

在测试中,我想意识到我在评论中所写的内容。

我可以做到,但是每次变得非常混乱。 我曾经为某些东西调用flexmock(例如,ExternalClass.get('arg1')将使用flexmock(ExternalClass).should_return('arg').with_args('arg') # etc...进行模拟),但是我厌倦了使用不同的测试库进行模拟。

我只想使用模拟库,但是我很难找到一种一致的方法。

1 个答案:

答案 0 :(得分:0)

我喜欢使用python的unittest lib。具体来说, <Grid> <Grid.Resources> <local:IsZeroToHiddenConverter x:Key="IsZeroToHiddenConverter"/> </Grid.Resources> <Grid VerticalAlignment="Center" HorizontalAlignment="Center"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <TextBox x:Name="Tb1" Grid.Row="0" Width="100" Margin="5" Text="{Binding Path=Amount, StringFormat=F2, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/> <TextBox x:Name="Tb2" Grid.Row="1" Width="100" Margin="5" Visibility="{Binding Path=Amount, Converter={StaticResource IsZeroToHiddenConverter}}"/> <TextBox x:Name="Tb3" Grid.Row="2" Width="100" Margin="5"/> </Grid> </Grid> 是在单元测试功能中自定义side effectsreturn value的绝佳库。

它们可以按如下方式使用:

unittest.mock

class Some(object): """ You want to test this class external_lib is an external component we cannot test """ def __init__(self, external_lib): self.lib = external_lib def create_index(self, unique_index): """ Create an index. """ try: self.lib.create(index=unique_index) # mock this return True except MyException as e: self.logger.error(e.__dict__, color="red") return False class MockLib(): pass class TestSome(unittest.TestCase): def setUp(self): self.lib = MockLib() self.some = Some(self.lib) def test_create_index(self): # This will test the method returns True if everything went fine self.some.create_index = MagicMock(return_value={}) self.assertTrue(self.some.create_index("test-index")) def test_create_index_fail(self): # This will test the exception is handled and return False self.some.create_index = MagicMock(side_effect=MyException("error create")) self.assertFalse(self.some.create_index("test-index")) 类文件放在TestSome()之类的位置,然后运行:

your-codebase-path/tests

我希望它有用。