写一个最简单的unittest的代码
时间: 2024-03-14 11:48:18 浏览: 21
下面是一个最简单的 `unittest` 代码示例:
```python
import unittest
class TestStringMethods(unittest.TestCase):
def test_upper(self):
self.assertEqual('hello'.upper(), 'HELLO')
def test_isupper(self):
self.assertTrue('HELLO'.isupper())
self.assertFalse('Hello'.isupper())
def test_split(self):
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
with self.assertRaises(TypeError):
s.split(2)
if __name__ == '__main__':
unittest.main()
```
该代码定义了一个名为 `TestStringMethods` 的测试类,其中包含了三个测试方法 `test_upper()`、`test_isupper()` 和 `test_split()`。这些测试方法使用了 `assert` 语句来验证一些字符串方法的行为是否符合预期。
在 `if __name__ == '__main__'` 代码块中,我们调用了 `unittest.main()` 函数来运行所有的测试方法。当运行测试时,`unittest` 模块会自动执行 `setUp()`、`tearDown()` 和各个测试方法,并输出测试结果。
如果以上代码保存为 `test_sample.py` 文件,你可以通过在命令行中执行 `python test_sample.py` 来运行测试。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)