반응형
방법 1 : 모의 객체를 만들어 사용하면됩니다. 코드는 다음과 같습니다.
def test_one (self):
mock = Mock()
mock.method.return_value = True
self.sut.something(mock) # This should called mock.method and checks the result.
self.assertTrue(mock.method.called)
방법 2 : patch를 사용하여 모형을 만듭니다. 코드는 다음과 같습니다.
@patch("MyClass")
def test_two (self, mock):
instance = mock.return_value
instance.method.return_value = True
self.sut.something(instance) # This should called mock.method and checks the result.
self.assertTrue(instance.method.called)
두 방법 모두 동일한 작업을 수행합니다. 차이점이 확실하지 않습니다.
누구든지 나를 깨달을 수 있습니까?
해결 방법
>>> class MyClass(object):
... def __init__(self):
... print 'Created MyClass@{0}'.format(id(self))
...
>>> def create_instance():
... return MyClass()
...
>>> x = create_instance()
Created MyClass@4299548304
>>>
>>> @mock.patch('__main__.MyClass')
... def create_instance2(MyClass):
... MyClass.return_value = 'foo'
... return create_instance()
...
>>> i = create_instance2()
>>> i
'foo'
>>> def create_instance():
... print MyClass
... return MyClass()
...
>>> create_instance2()
<mock.Mock object at 0x100505d90>
'foo'
>>> create_instance()
<class '__main__.MyClass'>
Created MyClass@4300234128
<__main__.MyClass object at 0x100505d90>
patch
는 호출하는 함수에서 클래스 사용을 제어 할 수있는 방식으로 MyClass
를 대체합니다. 클래스를 패치하면 클래스에 대한 참조가 모의 인스턴스로 완전히 대체됩니다.
mock.patch
는 일반적으로 테스트 내부에 클래스의 새 인스턴스를 만드는 무언가를 테스트 할 때 사용됩니다. mock.Mock
인스턴스가 더 명확하고 선호됩니다. self.sut.something
메서드가 인스턴스를 매개 변수로받는 대신 MyClass
의 인스턴스를 생성했다면 mock.patch
가 적절할 것입니다. 여기.
참조 페이지 https://stackoverflow.com/questions/8180769
반응형
'파이썬' 카테고리의 다른 글
파이썬 목록의 내용을 가져 와서 다른 목록에 추가 (0) | 2020.09.24 |
---|---|
파이썬 Python의 고유 세션 ID (0) | 2020.09.24 |
파이썬의 2 차원 배열 (0) | 2020.09.24 |
파이썬에서 변수 인수 (kwargs)에서 클래스 속성을 설정하는 방법 (0) | 2020.09.24 |
파이썬 반복기 변수없이 Python for range 루프를 구현할 수 있습니까? (0) | 2020.09.24 |
댓글