python单元测试

python3直接使用unittest标准库

1. 需要继承unittest.TestCase类

2. 测试方法需要取名为test_xxx()

import unittest
from unittest import mock
from unittest.mock import patch

import UnitTestDemo


class Caculator:
    def add(self, n1, n2):
        return n1 + n2


def add_and_multiply(n1, n2):
    sum_res = n1 + n2
    multi_res = multiply_func(n1, n2)
    return sum_res, multi_res


def multiply_func(n1, n2):
    return n1 * n2


class TestAdd(unittest.TestCase):
    def test_add(self):
        caculator = Caculator()
        caculator.add = mock.Mock(return_value=100)
        res = caculator.add(1, 10)
        print(f"sum:{res}")
        self.assertEqual(res, 100)

    @patch("mock_demo.multiply_func")
    def test_add_and_multiply(self, _mock_multiply):
        _mock_multiply.return_value = 1000
        sum_res, multi_res = add_and_multiply(10, 20)
        print(f"sum:{sum_res}, multi_res:{multi_res}")


if __name__ == __main__:
    print(UnitTestDemo.mock_demo.multiply_func(10, 11))

 

python单元测试

上一篇:LeetCode——797. 所有可能的路径(Java)


下一篇:aspnet_Users中LastActiveDate的问题