对于没有返回值的函数怎么用mock进行测试
时间: 2023-08-11 17:04:07 浏览: 115
对于没有返回值的函数,我们可以使用Mock来判断它是否被正确调用。具体方法是使用Mock对象的assert_called_once()方法,这个方法会检查Mock对象是否被正确调用了一次。
以下是一个例子:
假设我们有一个函数print_hello(),它没有返回值,只是打印一句话。
```python
def print_hello():
print("Hello!")
```
现在我们想测试它是否被正确调用了一次,我们可以使用Mock对象来模拟它的调用,并使用assert_called_once()方法来判断它是否被正确调用了一次。
```python
from unittest.mock import Mock
def test_print_hello():
mock_print_hello = Mock()
print_hello = mock_print_hello
# 调用函数
print_hello()
# 判断函数是否被正确调用了一次
mock_print_hello.assert_called_once()
```
在上面的例子中,我们首先创建一个Mock对象mock_print_hello,然后将print_hello函数替换为mock_print_hello。然后我们调用print_hello函数,并使用assert_called_once()方法来判断mock_print_hello是否被正确调用了一次。如果mock_print_hello没有被正确调用,assert_called_once()方法将会抛出一个AssertionError异常。