try:
context.do_something()
except ValueError:
return False
我确实测试了这个特定的代码。当我使用旁注的时候,例如
context = mock.MagicMoc()
context.do_something.side_effect = ValueError
当我使用pytest.raises时,测试通过了,但是代码没有被测试。我尝试过使用assert,但是失败了。
有什么建议吗
发布于 2020-02-13 09:25:59
我假设您正在将try/except代码包装在您想要测试的函数中。这里有两个选项来测试它。
1)在更改函数以重新引发ValueError之后,使用context manager检查是否引发了异常(尽管如果您不打算使用它做任何事情,那么您也可以在一开始就不捕获它):
from unittest import TestCase, mock
def do_something(c):
try:
c.do_something()
except ValueError as e:
raise e
class TestSomething(TestCase):
def test_do_something(self):
context = mock.MagicMock()
context.do_something.side_effect = ValueError
with self.assertRaises(ValueError):
do_something(context)
2)在函数的成功控制路径中返回True,然后在测试中检查这个条件:
from unittest import TestCase, mock
def do_something(c):
try:
c.do_something()
return True
except ValueError as e:
return False
class TestSomething(TestCase):
def test_do_something(self):
context = mock.MagicMock()
context.do_something.side_effect = ValueError
self.assertTrue(do_something(context))
https://stackoverflow.com/questions/60198255
复制相似问题