当前位置:   article > 正文

ChatGPT与单元测试_gpt单元测试

gpt单元测试

 

2024软件测试面试刷题,这个小程序(永久刷题),靠它快速找到工作了!(刷题APP的天花板)-CSDN博客文章浏览阅读1.3k次,点赞59次,收藏8次。你知不知道有这么一个软件测试面试的刷题小程序。里面包含了面试常问的软件测试基础题,web自动化测试、app自动化测试、接口测试、性能测试、自动化测试、安全测试及一些常问到的人力资源题目。最主要的是他还收集了像阿里、华为这样的大厂面试真题,还有互动交流板块……​编辑https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5501icon-default.png?t=N7T8https://blog.csdn.net/AI_Green/article/details/134931243?spm=1001.2014.3001.5501

1 最基本的单元测试   

1.1Java计算器  

输入  

下面一段代码生成JUnit5架构的单元测试用例

  1. package com.jerry;
  2. public class Calculator{
  3. private static int result;
  4. public void add(int n) {
  5. result = result + n;
  6. }
  7. public void substract(int n) {
  8. result = result - n;
  9. }
  10. public void multiply(int n) {
  11. result = result * n;
  12. }
  13. public void divide(int n){
  14. try {
  15. result = result / n;
  16. }catch(ArithmeticException ex){
  17. System.out.println(ex);
  18. throw new ArithmeticException("The n not allowed to 0!!");
  19. }
  20. }
  21. }

ChatGPT回答   

下面是基于你提供的代码生成的JUnit5架构的单元测试用例:

  1. package com.jerry;
  2. import org.junit.jupiter.api.BeforeEach;
  3. import org.junit.jupiter.api.Test;
  4. import static org.junit.jupiter.api.Assertions.*;
  5. public class CalculatorTest {
  6. private Calculator calculator;
  7. @BeforeEach
  8. public void setUp() {
  9. calculator = new Calculator();
  10. calculator.result = 10; // 初始值
  11. }
  12. @Test
  13. public void testAdd() {
  14. calculator.add(5);
  15. assertEquals(15, calculator.result);
  16. }
  17. @Test
  18. public void testSubstract() {
  19. calculator.substract(3);
  20. assertEquals(7, calculator.result);
  21. }
  22. @Test
  23. public void testMultiply() {
  24. calculator.multiply(2);
  25. assertEquals(20, calculator.result);
  26. }
  27. @Test
  28. public void testDivide() {
  29. calculator.divide(2);
  30. assertEquals(5, calculator.result);
  31. }
  32. @Test
  33. public void testDivideByZero() {
  34. ArithmeticException exception = assertThrows(ArithmeticException.class, () -> calculator.divide(0));
  35. assertEquals("The n not allowed to 0!!", exception.getMessage());
  36. }
  37. }

这些测试用例覆盖了Calculator类中的所有方法,并且检查了各种情况下的预期行为。

运行代码  

测试通过

1.2 Python计算器  

unittest架构  

输入  

下面代码生成unittest架构的单元测试用例

  1. #!/usr/bin/env python
  2. #coding:utf-8
  3. __metaclass_=type
  4. class calculator:
  5. def __init__(self,result):
  6. self.result=int(result)
  7. def add(self,n):
  8. self.result = self.result + n
  9. def subs(self,n):
  10. self.result = self.result - n
  11. def multiply(self,n):
  12. self.result = self.result * n
  13. def divide(self,n):
  14. try:
  15. self.result = self.result/n
  16. except ZeroDivisionError:
  17. print ("除数不能为零")
  18. self.result = 0
  19. def getResult(self):
  20. return self.result;
  21. def clear(self):
  22. self.result = 0;

ChatGPT回答 

  1. import unittest
  2. from calculator import calculator
  3. class TestCalculator(unittest.TestCase):
  4. def setUp(self):
  5. self.calc = calculator(10)
  6. def test_add(self):
  7. self.calc.add(5)
  8. self.assertEqual(self.calc.getResult(), 15)
  9. def test_subs(self):
  10. self.calc.subs(3)
  11. self.assertEqual(self.calc.getResult(), 7)
  12. def test_multiply(self):
  13. self.calc.multiply(2)
  14. self.assertEqual(self.calc.getResult(), 20)
  15. def test_divide(self):
  16. self.calc.divide(2)
  17. self.assertEqual(self.calc.getResult(), 5)
  18. def test_divide_by_zero(self):
  19. self.calc.divide(0)
  20. self.assertEqual(self.calc.getResult(), 0)
  21. def test_clear(self):
  22. self.calc.clear()
  23. self.assertEqual(self.calc.getResult(), 0)
  24. if __name__ == '__main__':
  25. unittest.main()

请注意,这段代码假设已经有一个名为calculator的类定义在calculator.py文件中。测试用例中的setUp方法用于初始化calculator实例,test_add、test_subs、test_multiply、test_divide、test_divide_by_zero和test_clear分别对calculator类的各个方法进行测试。

运行  

测试通过    

pytest架构  

输入  

下面代码生成pytest架构的单元测试用例

  1. #!/usr/bin/env python
  2. #coding:utf-8
  3. __metaclass_=type
  4. class calculator:
  5. def __init__(self,result):
  6. self.result=int(result)
  7. def add(self,n):
  8. self.result = self.result + n
  9. def subs(self,n):
  10. self.result = self.result - n
  11. def multiply(self,n):
  12. self.result = self.result * n
  13. def divide(self,n):
  14. try:
  15. self.result = self.result/n
  16. except ZeroDivisionError:
  17. print ("除数不能为零")
  18. self.result = 0
  19. def getResult(self):
  20. return self.result;
  21. def clear(self):
  22. self.result = 0;

ChatGPT回答   

下面是将给定的计算器类转换为pytest架构的单元测试用例的代码示例:

  1. import pytest
  2. class TestCalculator:
  3. @pytest.fixture
  4. def calculator_instance(self):
  5. from your_module import calculator # 将your_module替换为你的模块名
  6. calc = calculator(10) # 假设初始结果为10
  7. yield calc
  8. def test_add(self, calculator_instance):
  9. calculator_instance.add(5)
  10. assert calculator_instance.getResult() == 15
  11. def test_subs(self, calculator_instance):
  12. calculator_instance.subs(3)
  13. assert calculator_instance.getResult() == 7
  14. def test_multiply(self, calculator_instance):
  15. calculator_instance.multiply(2)
  16. assert calculator_instance.getResult() == 20
  17. def test_divide(self, calculator_instance):
  18. calculator_instance.divide(5)
  19. assert calculator_instance.getResult() == 2
  20. def test_divide_by_zero(self, calculator_instance):
  21. calculator_instance.divide(0)
  22. assert calculator_instance.getResult() == 0
  23. def test_clear(self, calculator_instance):
  24. calculator_instance.clear()
  25. assert calculator_instance.getResult() == 0

在这个示例中,我们使用pytest的@pytest.fixture装饰器创建了一个fixture,用于实例化计算器类。然后,我们定义了多个测试方法,每个方法对应计算器类的不同功能,并使用assert语句来验证计算结果是否符合预期。请将your_module替换为你的模块名。

修改代码  
from your_module import calculator  # 将your_module替换为你的模块名

改为

from alculator import calculator
运行  

测试通过    

2 Mock技术  

2.1 Java Mock的技术  

输入  

对下面Account.java、AccountManager.java AccountService.java 3个文件书写基于JUnit5和Mockito的单元测试用例

Account.java

  1. package com.Account.JUnit5Project;
  2. public class Account
  3. {
  4. private String accountId;
  5. private long balance;
  6. public Account(String accountId, long initialBalance)
  7. {
  8. this.accountId = accountId;
  9. this.balance = initialBalance;
  10. }
  11. //借记
  12. public void debit( long amount )
  13. {
  14. this.balance -= amount;
  15. }
  16. //信用
  17. public void credit( long amount )
  18. {
  19. this.balance += amount;
  20. }
  21. public long getBalance()
  22. {
  23. return this.balance;
  24. }
  25. }

AccountManager.java

  1. package com.Account.JUnit5Project;
  2. import com.Account.JUnit5Project.Account;
  3. public interface AccountManager
  4. {
  5. Account findAccountForUser(String userId );
  6. void updateAccount(Account account );
  7. }

AccountService.java

  1. package com.Account.JUnit5Project;
  2. import com.Account.JUnit5Project.Account;
  3. import com.Account.JUnit5Project.AccountManager;
  4. public class AccountService
  5. {
  6. //使用的帐户管理器实现
  7. private AccountManager accountManager;
  8. //设置帐户管理器实现的设置方法
  9. public void setAccountManager( AccountManager manager )
  10. {
  11. this.accountManager = manager;
  12. }
  13. //一个设置客户经理实现从账户到账户的senderId beneficiaryId setter方法。
  14. //senderId:转出方Id
  15. //beneficiaryId:收益方Id
  16. //amount:金额
  17. public void transfer( String senderId, String beneficiaryId, long amount )
  18. {
  19. //初始化转出方与收益方,findAccountForUser为接口类方法
  20. Account sender = this.accountManager.findAccountForUser( senderId );
  21. Account beneficiary = this.accountManager.findAccountForUser( beneficiaryId );
  22. //转入和收益
  23. sender.debit( amount );
  24. beneficiary.credit( amount );
  25. //更新,updateAccount为接口类方法
  26. this.accountManager.updateAccount( sender );
  27. this.accountManager.updateAccount( beneficiary );
  28. }
  29. }

ChatGPT回答   

下面是基于JUnit5和Mockito的单元测试用例,分别针对Account.java、AccountManager.java和AccountService.java这三个类进行测试。

  1. package com.Account.JUnit5Project;
  2. import org.junit.jupiter.api.Test;
  3. import org.junit.jupiter.api.BeforeEach;
  4. import static org.junit.jupiter.api.Assertions.*;
  5. import static org.mockito.Mockito.*;
  6. public class AccountTest {
  7. private Account account;
  8. @BeforeEach
  9. public void setUp() {
  10. account = new Account("12345", 1000);
  11. }
  12. @Test
  13. public void testDebit() {
  14. account.debit(500);
  15. assertEquals(500, account.getBalance());
  16. }
  17. @Test
  18. public void testCredit() {
  19. account.credit(200);
  20. assertEquals(1200, account.getBalance());
  21. }
  22. }
  1. package com.Account.JUnit5Project;
  2. import org.junit.jupiter.api.Test;
  3. import static org.junit.jupiter.api.Assertions.*;
  4. import static org.mockito.Mockito.*;
  5. public class AccountServiceTest {
  6. private AccountService accountService;
  7. private AccountManager accountManager;
  8. @BeforeEach
  9. public void setUp() {
  10. accountService = new AccountService();
  11. accountManager = mock(AccountManager.class);
  12. accountService.setAccountManager(accountManager);
  13. }
  14. @Test
  15. public void testTransfer() {
  16. Account sender = new Account("sender123", 1000);
  17. Account beneficiary = new Account("beneficiary456", 2000);
  18. when(accountManager.findAccountForUser("sender123")).thenReturn(sender);
  19. when(accountManager.findAccountForUser("beneficiary456")).thenReturn(beneficiary);
  20. accountService.transfer("sender123", "beneficiary456", 500);
  21. assertEquals(500, sender.getBalance());
  22. assertEquals(2500, beneficiary.getBalance());
  23. verify(accountManager, times(1)).updateAccount(sender);
  24. verify(accountManager, times(1)).updateAccount(beneficiary);
  25. }
  26. }

在这里,我们使用了JUnit5的注解@BeforeEach和@Test来初始化测试环境和编写测试用例。同时,使用了Mockito来模拟AccountManager接口的实现,并对AccountService的transfer方法进行测试。    

希望这个示例对你有所帮助!

运行代码  

没有定义

import org.junit.jupiter.api.BeforeEach;

修改代码  

加上import org.junit.jupiter.api.BeforeEach;

测试通过

2.2  python Mock技术  

输入  

被测代码

core.py

  1. #!/usr/bin/env python
  2. #coding:utf-8
  3. class Score:
  4. def __init__(self):
  5. pass
  6. def get_score_by_student_id(self, student_id):
  7. pass
  8. def get_address_average_score(self,student_id):
  9. # 成绩信息:{"Chinese":95,"Mathematics":97,"English":100}
  10. score = self.get_score_by_student_id(student_id)
  11. return (score.get("Chinese")+ score.get("Mathematics")+ score.get("English"))/3

基于core.py使用,使用from unittest import mock和pytest-mock生成单元测试代码

ChatGPT回答  

你可以使用unittest.mock和pytest-mock来生成基于core.py的单元测试代码。首先,你需要安装pytest-mock库:

pip3 install pytest-mock

然后,你可以创建一个测试文件test_core.py,并在其中使用unittest.mock和pytest-mock来编写测试代码。以下是一个可能的示例:

test_core.py

  1. import pytest
  2. from unittest.mock import Mock
  3. from core import Score
  4. def test_get_address_average_score(mocker):
  5. # 创建一个Score实例
  6. score = Score()
  7. # 使用pytest-mock的patch来模拟get_score_by_student_id方法
  8. mock_get_score = mocker.patch.object(score, 'get_score_by_student_id')
  9. mock_get_score.return_value = {"Chinese": 95, "Mathematics": 97, "English": 100}
  10. # 测试get_address_average_score方法
  11. assert score.get_address_average_score(123) == (95 + 97 + 100) / 3

在这个示例中,我们使用pytest-mock的mocker对象来模拟get_score_by_student_id方法的返回值,并使用assert语句来验证get_address_average_score方法的行为。

你可以根据实际情况修改测试用例,并使用更多的unittest.mock和pytest-mock功能来编写更复杂的测试代码。希望这可以帮助到你!

运行代码  

测试通过

3 单元测试覆盖率  

3.1 Java单元测试覆盖率  

输入  

产品代码如下

process.py

  1. class process:
  2. def myfunction(self,x, a, b):
  3. if ((a>1) and (b==0)):x=x/a
  4. if((a==2) or (x>1)):x=x+1
  5. return x

test_process.py

  1. #!/usr/bin/env python
  2. #coding:utf-8
  3. from process import process
  4. import unittest
  5. class TestProcess(unittest.TestCase):
  6. p= process()
  7. def test_case1(self):
  8. self.assertEqual(self.p.myfunction(1,2,0),1)
  9. def test_case2(self):
  10. self.assertEqual(self.p.myfunction(0,4,0),0)
  11. def test_case3(self):
  12. self.assertEqual(self.p.myfunction(1,2,1),2)
  13. def test_case4(self):
  14. self.assertEqual(self.p.myfunction(0,1,1),0)
  15. if __name__ == '__main__':
  16. unittest.main()

给出测试代码test_process.py测试产品代码process.py后的测试覆盖率    

ChatGPT回答  

你可以使用coverage工具来计算Python代码的测试覆盖率。首先,确保你已经安装了coverage包。然后在命令行中运行以下命令:

coverage run test_process.py

这将运行你的测试用例并收集覆盖率数据。接下来,运行以下命令来生成覆盖率报告:

coverage report -m

这将显示测试覆盖率的详细报告,包括哪些行被测试覆盖了,哪些行没有被测试覆盖。

结论

ChatGPT没有给答案,经给了个方法

3.2 Python单元测试覆盖率  

输入  

产品代码如下

process.java

  1. package com.jerry;
  2. public class process {
  3. public int myfunction(int x, int a, int b) {
  4. if ((a>1) && (b==0)) x=x/a;
  5. if((a==2) || (x>1)) x=x+1;
  6. return x;
  7. }
  8. }

testprocess.java

  1. package com.jerry;
  2. import static org.junit.Assert.*;
  3. import org.junit.Test;
  4. public class Testprocess {
  5. private static process p = new process();
  6. @Test
  7. public void test1() {
  8. assertEquals(p.myfunction(1,2,0),1);
  9. }
  10. @Test
  11. public void test2() {
  12. assertEquals(p.myfunction(0,4,0),0);
  13. }
  14. @Test
  15. public void test3() {
  16. assertEquals(p.myfunction(1,2,0),1);
  17. }
  18. @Test
  19. public void test4() {
  20. assertEquals(p.myfunction(0,1,1),0);
  21. }
  22. }

给出测试代码testprocess.java测试产品代码process.java后的测试覆盖率    

ChatGPT回答   

为了计算测试覆盖率,你可以使用JaCoCo代码覆盖率工具。首先,确保你的项目中已经包含了JaCoCo插件。然后,你可以使用构建工具(比如Maven或Gradle)来生成测试覆盖率报告。

如果你使用Maven作为构建工具,你可以在项目的pom.xml文件中添加JaCoCo插件配置:

  1. <build>
  2. <plugins>
  3. <plugin>
  4. <groupId>org.jacoco</groupId>
  5. <artifactId>jacoco-maven-plugin</artifactId>
  6. <version>0.8.7</version>
  7. <executions>
  8. <execution>
  9. <goals>
  10. <goal>prepare-agent</goal>
  11. </goals>
  12. </execution>
  13. <execution>
  14. <id>report</id>
  15. <phase>test</phase>
  16. <goals>
  17. <goal>report</goal>
  18. </goals>
  19. </execution>
  20. </executions>
  21. </plugin>
  22. </plugins>
  23. </build>

然后,在命令行中执行以下命令来运行测试并生成覆盖率报告:

mvn clean test

执行完上述命令后,你可以在项目的target目录中找到JaCoCo生成的测试覆盖率报告。报告通常以HTML格式呈现,你可以在浏览器中打开查看详细的覆盖率信息。

通过这个过程,你就可以得到测试代码testprocess.java对产品代码process.java的测试覆盖率情况。    

结论

ChatGPT没有给答案,经给了个方法

行动吧,在路上总比一直观望的要好,未来的你肯定会感谢现在拼搏的自己!如果想学习提升找不到资料,没人答疑解惑时,请及时加入群: 786229024,里面有各种测试开发资料和技术可以一起交流哦。

最后: 下方这份完整的软件测试视频教程已经整理上传完成,需要的朋友们可以自行领取【保证100%免费】在这里插入图片描述
软件测试面试文档
我们学习必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有字节大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/200701
推荐阅读
相关标签
  

闽ICP备14008679号