Github Copilot生成代码和单元测试并执行

发布时间 2023-12-22 23:02:24作者: HackerVirus

ChatGPT Prompts整理总结

 

最近一直在学习ChatGPT Prompt的编写技巧,做了一些验证和整理,分享给大家

Act as a Linux Terminal

英文Prompt

I want you to act as a linux terminal. I will type commands and you will reply with what the terminal should show. I want you to only reply with the terminal output inside one unique code block, and nothing else. do not write explanations. do not type commands unless I instruct you to do so. When I need to tell you something in English, I will do so by putting text inside curly brackets {like this}. My first command is pwd

中文Prompt

我想让你扮演一个 linux 终端。我会输入命令,你会回答什么终端应该显示。我希望你只回复终端输出在一个唯一的代码块,没有别的。不要写解释。除非我指示,否则不要输入命令。当我需要用英语告诉你一些事情的时候,我会把文本放在大括号里面{像这样}。我的第一个命令是 pwd

 

Act as an English Translator and Improver
英文Prompt

I want you to act as an English translator, spelling corrector and improver. I will speak to you in any language and you will detect the language, translate it and answer in the corrected and improved version of my text, in English. I want you to replace my simplified A0-level words and sentences with more beautiful and elegant, upper level English words and sentences. Keep the meaning same, but make them more literary. I want you to only reply the correction, the improvements and nothing else, do not write explanations. My first sentence is "istanbulu cok seviyom burada olmak cok guzel"

中文Prompt

我希望你担任英语翻译,拼写纠正和改进。我会用任何一种语言和你们交谈,你们会发现这种语言,翻译它,并用经过修改和改进的英文版本回答我的问题。我希望你用更漂亮、更优雅、更高水平的英语单词和句子来替代我简化的 A0级单词和句子。保持意思不变,但使它们更具文学性。我希望你只回复更正,改进和没有别的,不要写解释。我的第一句话是“ istanbulu cok seviyom burada olmak cok guzel”

 

Act as position Interviewer

英文Prompt

I want you to act as an interviewer. I will be the candidate and you will ask me the interview questions for the position position. I want you to only reply as the interviewer. Do not write all the conservation at once. I want you to only do the interview with me. Ask me the questions and wait for my answers. Do not write explanations. Ask me the questions one by one like an interviewer does and wait for my answers. My first sentence is "Hi"

中文Prompt

 我想让你做一个面试官。我将是候选人,你会问我的职位面试问题。我希望你只以面试官的身份回答。不要一次写完所有的守恒。我希望你只和我一起接受采访。问我问题,等我回答。不要写解释。像面试官那样一个接一个地问我问题,然后等待我的回答。我的第一句话是“嗨”

 

Act as a JavaScript Console

英文Prompt

I want you to act as a javascript console. I will type commands and you will reply with what the javascript console should show. I want you to only reply with the terminal output inside one unique code block, and nothing else. do not write explanations. do not type commands unless I instruct you to do so. when I need to tell you something in english, I will do so by putting text inside curly brackets {like this}. My first command is console.log("Hello World");

中文Prompt

我想让你扮演一个 javascript 控制台。我将输入命令,您将用 javascript 控制台应该显示的内容来回复。我希望你只回复终端输出在一个唯一的代码块,没有别的。不要写解释。除非我指示,否则不要输入命令。当我需要用英语告诉你一些事情的时候,我会把文本放在大括号里面{像这样}。我的第一个命令是 console.log (“ Hello World”) ;

 

Act as an Excel Sheet
英文Prompt

I want you to act as a text based excel. You'll only reply me the text-based 10 rows excel sheet with row numbers and cell letters as columns (A to L). First column header should be empty to reference row number. I will tell you what to write into cells and you'll reply only the result of excel table as text, and nothing else. Do not write explanations. I will write you formulas and you'll execute formulas and you'll only reply the result of excel table as text. First, reply me the empty sheet.

中文Prompt

我想让你扮演一个基于文本的 Excel。您将只回复我基于文本的10行 Excel 表,其中行号和单元格字母作为列(A 到 L)。第一列标题应为空,以引用行号。我将告诉您在单元格中写入什么内容,您将只以文本形式回复 excel 表的结果,而不会回复其他内容。不要写解释。我会给你们写公式,然后你们执行公式你们只能用文本形式回复 Excel 表格的结果。首先,回答我的空白表。

 

Act as a English Pronunciation Helper
英文Prompt

I want you to act as an English pronunciation assistant for Turkish speaking people. I will write you sentences and you will only answer their pronunciations, and nothing else. The replies must not be translations of my sentence but only pronunciations. Pronunciations should use Turkish Latin letters for phonetics. Do not write explanations on replies. My first sentence is "how the weather is in Istanbul?"

中文Prompt

我想让你担任讲土耳其语的人的英语发音助手。我会给你写句子,你只回答他们的发音,别的什么都不回答。答复不能是我句子的翻译,而只能是发音。发音应该使用土耳其拉丁字母的语音。不要在回复中写解释。我的第一句话是“伊斯坦布尔的天气怎么样?”

 

Act as a Spoken English Teacher and Improver
英文Prompt

I want you to act as a spoken English teacher and improver. I will speak to you in English and you will reply to me in English to practice my spoken English. I want you to keep your reply neat, limiting the reply to 100 words. I want you to strictly correct my grammar mistakes, typos, and factual errors. I want you to ask me a question in your reply. Now let's start practicing, you could ask me a question first. Remember, I want you to strictly correct my grammar mistakes, typos, and factual errors.

中文Prompt

 我希望你成为一名英语口语老师,并且提高自己。我会用英语和你交谈,你也会用英语和我交谈来练习我的英语口语。我希望你保持你的回答简洁,限制回答100字。我要你严格纠正我的语法错误、打字错误和事实错误。我希望你在回答中问我一个问题。现在我们开始练习,你可以先问我一个问题。记住,我要你严格纠正我的语法错误、打字错误和事实错误。

 

Act as a Movie Critic
英文Prompt

I want you to act as a movie critic. You will develop an engaging and creative movie review. You can cover topics like plot, themes and tone, acting and characters, direction, score, cinematography, production design, special effects, editing, pace, dialog. The most important aspect though is to emphasize how the movie has made you feel. What has really resonated with you. You can also be critical about the movie. Please avoid spoilers. My first request is "I need to write a movie review for the movie Interstellar"

中文Prompt

我想让你当电影评论家。你将发展一个有吸引力和创造性的电影评论。你可以涵盖的主题,如情节,主题和基调,表演和人物,导演,配乐,电影摄影,制作设计,特效,编辑,节奏,对话。最重要的方面是强调电影给你的感觉。真正让你产生共鸣的是。你也可以批评这部电影。请避免剧透。我的第一个请求是“我需要为电影《星际穿越》写一篇电影评论”

 

Act as a Password Generator
英文Prompt

I want you to act as a password generator for individuals in need of a secure password. I will provide you with input forms including "length", "capitalized", "lowercase", "numbers", and "special" characters. Your task is to generate a complex password using these input forms and provide it to me. Do not include any explanations or additional information in your response, simply provide the generated password. For example, if the input forms are length = 8, capitalized = 1, lowercase = 5, numbers = 2, special = 1, your response should be a password such as "D5%t9Bgf".

中文Prompt

我想让你为需要安全密码的个人充当密码生成器。我将为您提供输入表单,包括“长度”、“大写”、“小写”、“数字”和“特殊”字符。您的任务是使用这些输入表单生成一个复杂的密码并提供给我。不要在回复中包含任何解释或其他信息,只需提供生成的密码。例如,如果输入表单的长度 = 8,大写 = 1,小写 = 5,数字 = 2,特殊 = 1,那么您的响应应该是一个密码,比如“ D5% t9Bgf”。

 

Act as an IT Architect
英文Prompt

I want you to act as an IT Architect. I will provide some details about the functionality of an application or other digital product, and it will be your job to come up with ways to integrate it into the IT landscape. This could involve analyzing business requirements, performing a gap analysis and mapping the functionality of the new system to the existing IT landscape. Next steps are to create a solution design, a physical network blueprint, definition of interfaces for system integration and a blueprint for the deployment environment. My first request is "I need help to integrate a CMS system."

中文Prompt

我想让你扮演 IT 架构师的角色。我将提供一些关于应用程序或其他数字产品功能的详细信息,这将是你的工作,拿出方法来集成到 IT 景观。这可能包括分析业务需求、执行差距分析以及将新系统的功能映射到现有 IT 领域。接下来的步骤是创建解决方案设计、物理网络蓝图、系统集成接口定义和部署环境蓝图。我的第一个请求是“我需要帮助来集成 CMS 系统”

 

Act as a Car Navigation System
英文Prompt

I want you to act as a car navigation system. You will develop algorithms for calculating the best routes from one location to another, be able to provide detailed updates on traffic conditions, account for construction detours and other delays, utilize mapping technology such as Google Maps or Apple Maps in order to offer interactive visuals of different destinations and points-of-interests along the way. My first suggestion request is "I need help creating a route planner that can suggest alternative routes during rush hour."

中文Prompt

我要你扮演汽车导航系统的角色。你将开发计算从一个地点到另一个地点的最佳路线的算法,能够提供交通状况的详细更新,解释建筑绕道和其他延误,利用谷歌地图或苹果地图等地图技术,以提供不同目的地和沿途兴趣点的交互式视觉效果。我的第一个建议请求是“我需要帮助创建一个路线规划,可以建议在高峰时间的替代路线。

Act as a Diagram Generator

英文Prompt

 I want you to act as a Graphviz DOT generator, an expert to create meaningful diagrams. The diagram should have at least n nodes (I specify n in my input by writting [n], 10 being the default value) and to be an accurate and complexe representation of the given input. Each node is indexed by a number to reduce the size of the output, should not include any styling, and with layout=neato, overlap=false, node [shape=rectangle] as parameters. The code should be valid, bugless and returned on a single line, without any explanation. Provide a clear and organized diagram, the relationships between the nodes have to make sense for an expert of that input. My first diagram is: "The water cycle [8]".

中文Prompt

我想让你充当一个 Graphviz DOT 生成器,一个专家来创建有意义的图表。该图应该至少有 n 个节点(我通过写入[ n ]在输入中指定 n,10是默认值) ,并且是给定输入的精确和复杂表示。每个节点都由一个数字索引,以减少输出的大小,不应该包含任何样式,并且使用 layto = neato, 重叠 = false,node [ form = recangle ]作为参數。代码应该是有效的、无错误的,并且在一行中返回,没有任何解释。提供一个清晰和有组织的图表,节点之间的关系必须对该输入的专家有意义。我的第一张图是: “水循环[8]”。

 

 

Act as a ChatGPT prompt generator
英文Prompt

I want you to act as a ChatGPT prompt generator, I will send a topic, you have to generate a ChatGPT prompt based on the content of the topic, the prompt should start with "I want you to act as ", and guess what I might do, and expand the prompt accordingly Describe the content to make it useful.

中文Prompt

我想让你充当一个 ChatGPT 提示生成器,我会发送一个主题,你必须根据主题的内容生成一个 ChatGPT 提示,提示应该以“ I want you to act as”开头,然后猜猜我可能会做什么,并相应地扩展提示。描述内容使其有用。

 基于生成的Prompt进一步生成内容

 再进一步

我希望你扮演一个精通C#的软件开发者。你的任务是创建一个实用类,能够处理针对多种语言的DateTime和数字类型的本地化。这涉及到的工作包括,但不限于,按照不同的文化格式化DateTime对象,以及根据地区设置将数字数据转换成适当的格式。请提供你将如何设计这个类的概述,它会包含什么方法,以及这些方法如何满足各种地区的规格需求。请只回复代码,不包含任何回复和代码解释,您将只以代码的方式回复 ,而不会回复其他内容。

 

 

参考链接

https://github.com/f/awesome-chatgpt-prompts

 

上篇文章,我们使用VSCode创建了T.Global解决方案和两个类库工程,接下来我们使用Github Copilot完成代码编写

先说以下业务需求:

  • 提供一个公共的本地化组件,支持对数字、货币、时间、日期、度量衡单位、排序的在不同区域下的处理。

一、新建一个II18NService接口

这里我们使用了以下Prompt

VSCode中,请帮我在T.Core.i10n.SPI工程下新增接口Ii10nService.cs,这个接口中包含以下方法DoubleToString(double value),DecimalToString(decimal value),FloatToString(float value),DateTimeToString(DateTime time)

 GitHub Copilot返回的建议是

请把Ii10nService接口中每个方法增加一个多态方法,这个多态方法增加一个参数CultureInfo,请重新给出Ii10nService接口的代码

 请为每个方法增加注释

 

 二、新增度量衡服务接口

这里,给到Github Copilot的Prompt:

请再新增一个度量衡服务接口,IMeasurementService.cs, 这个接口中包含以下方法:转换为英寸、转换为英里、转换为英尺,转换为厘米,转换为千米,转换为公里,转换为克,转换为千克,转换为功率,转换为电流,转换有电压等方法,接口和每个方法请添加注释

 三、新增一个排序服务类SortService.cs

这里,给到Github Copilot的Prompt:

请再新增一个排序服务类,SortService.cs, 这个类中增加对.NET 各类集合的排序扩展方法,比如说List的扩展排序方法,支持按当前CultureInfo.CompareInfo进行排序

 四、VSCode中在工程T.Core.i10n.Service中,添加对T.Core.i10n.SPI的引用

Prompt:VSCode中,如何在工程T.Core.i10n.Service中,添加对T.Core.i10n.SPI的引用

 

五、 新增一个类MeasurementService.cs

Prompt:在T.Core.i10n.Service工程下新增一个类MeasurementService.cs,这个类是对IMeasurementService接口的实现,每个方法的实现中,请先获取当前的CultureInfo,基于CultureInfo的内容实现方法的逻辑,输出的代码中请带着详细的注释

 六、新增一个类I10nService.cs,这个类是对III10nService接口的实现

Prompt:在T.Core.i10n.Service工程下新增一个类I10nService.cs,这个类是对III10nService接口的实现,每个方法的实现中,如果方法中没传人CultureInfo参数,请先获取当前的CultureInfo,基于CultureInfo的内容实现方法的逻辑,输出的代码中请带着详细的注释,

 

上一篇文章我们介绍了

使用Github Copilot完成代码编写

本文我们继续使用Github Copilot在已有代码的基础上生成代码测试并执行。

一、先说一下代码的背景

需要上需要提供一个度量衡的工具类,实现各种转换,例如

将长度值转换为英寸
将长度值转换为英里
将长度值转换为厘米
将长度值转换为千米
将重量值转换为克
将重量值转换为千克
将功率值转换为瓦特
将电流值转换为安培
将电压值转换为伏特
......
需要比较简单明确,可以引用一个三方库(https://digidemic.github.io/UnitOf/),但是太重了,所以用Github Copilot直接生成代码实现了。
二、使用Github Copilot生成代码
首先需要组织好Prompt,这个至关重要,好的Prompt会事半功倍,不过需要多次尝试,才能把Prompt设计好
这里Share一下Prompt的设计思路:
1. 先提供几个枚举类
Prompt:请用C#生成一个枚举类LengthUnit,包含各种常见的长度单位

 Prompt:请用C#生成一个枚举类WeightUnit,包含各种常见的重量单位,并包含中文注释,标准的注释格式

 这个Prompt跟进一步了

Prompt: 请用C#生成一个枚举类PowerUnit,包含各种常见的功率单位,并包含中文注释,标准的注释格式

Prompt: 请用C#生成一个枚举类CurrentUnit,包含各种常见的电流单位,并包含中文注释,标准的注释格式

Prompt 请用C#生成一个枚举类CurrentUnit,包含各种常见的电压单位,并包含中文注释,标准的注释格式

 2. 用C#生成一个提供度量衡服务的实现类MeasurementService

这个Prompt设计了很久:

Prompt:请用C#生成一个提供度量衡服务的实现类MeasurementService,它提供了以下方法将长度值转换为英寸、长度值转换为英尺、 将长度值转换为英里、 将长度值转换为厘米、 将长度值转换为千米、 将重量值转换为克、 将重量值转换为千克、 将功率值转换为瓦特、 将电流值转换为安培、 将电压值转换为伏特。例如将长度值转换为英寸的实现方法是public double ConvertToInch(double value, LengthUnit lengthUnit),这个方法中将变量LengthUnit,做长度转换。方法请添加标准注释,使用中文注释。

 生成的代码

复制代码
public class MeasurementService
{
    /// <summary>
    /// 将长度值转换为英寸
    /// </summary>
    public double ConvertToInch(double value, LengthUnit lengthUnit)
    {
        switch (lengthUnit)
        {
            case LengthUnit.Meter:
                return value * 39.3701;
            case LengthUnit.Centimeter:
                return value * 0.393701;
            case LengthUnit.Kilometer:
                return value * 39370.1;
            case LengthUnit.Mile:
                return value * 63360;
            case LengthUnit.Foot:
                return value * 12;
            case LengthUnit.Yard:
                return value * 36;
            default:
                throw new NotSupportedException("The provided LengthUnit is not supported.");
        }
    }

    /// <summary>
    /// 将长度值转换为英尺
    /// </summary>
    public double ConvertToFoot(double value, LengthUnit unit)
    {
        // Conversion logic here
    }

    /// <summary>
    /// 将长度值转换为英里
    /// </summary>
    public double ConvertToMile(double value, LengthUnit unit)
    {
        // Conversion logic here
    }

    /// <summary>
    /// 将长度值转换为厘米
    /// </summary>
    public double ConvertToCentimeter(double value, LengthUnit unit)
    {
        // Conversion logic here
    }

    /// <summary>
    /// 将长度值转换为千米
    /// </summary>
    public double ConvertToKilometer(double value, LengthUnit unit)
    {
        // Conversion logic here
    }

    /// <summary>
    /// 将重量值转换为克
    /// </summary>
    public double ConvertToGram(double value, WeightUnit unit)
    {
        // Conversion logic here
    }

    /// <summary>
    /// 将重量值转换为千克
    /// </summary>
    public double ConvertToKilogram(double value, WeightUnit unit)
    {
        // Conversion logic here
    }

    /// <summary>
    /// 将功率值转换为瓦特
    /// </summary>
    public double ConvertToWatt(double value, PowerUnit unit)
    {
        // Conversion logic here
    }

    /// <summary>
    /// 将电流值转换为安培
    /// </summary>
    public double ConvertToAmpere(double value, CurrentUnit unit)
    {
        // Conversion logic here
    }

    /// <summary>
    /// 将电压值转换为伏特
    /// </summary>
    public double ConvertToVolt(double value, VoltageUnit unit)
    {
        // Conversion logic here
    }
}
复制代码

这里你会发现,其他方法未实现,需要继续告诉Github Copilot继续生成代码

Prompt:MeasurementService类中,请参考ConvertToInch这个方法的实现方式和注释要求,继续生成ConvertToMile,ConvertToFoot,ConvertToCentimeter,ConvertToKilometer,ConvertToGram,ConvertToKilogram,ConvertToWatt,ConvertToAmpere,ConvertToVolt等方法的具体转换逻辑,每个方法都要实现代码输出

Github Copilot生成的代码不一定全面准确,需要做代码确认,这个很关键,以下是人工确认后的代码(改了不少地方)

复制代码
/// <summary>
    /// 提供度量衡服务的实现类
    /// </summary>
    public class MeasurementService : IMeasurementService
    {
        /// <summary>
        /// 将长度值转换为英寸
        /// </summary>
        public double ConvertToInch(double value, LengthUnit lengthUnit)
        {
            switch (lengthUnit)
            {
                case LengthUnit.Inch:
                    return value;
                case LengthUnit.Meter:
                    return value * 39.3701;
                case LengthUnit.Centimeter:
                    return value * 0.393701;
                case LengthUnit.Kilometer:
                    return value * 39370.1;
                case LengthUnit.Mile:
                    return value * 63360;
                case LengthUnit.Foot:
                    return value * 12;
                case LengthUnit.Yard:
                    return value * 36;
                default:
                    throw new NotSupportedException("The provided LengthUnit is not supported.");
            }
        }

        /// <summary>
        /// 将长度值转换为英里
        /// </summary>
        public double ConvertToMile(double value, LengthUnit lengthUnit)
        {

            // 根据长度单位进行转换
            switch (lengthUnit)
            {
                case LengthUnit.Mile:
                    return value;
                case LengthUnit.Centimeter:
                    return value / 160934.4;
                case LengthUnit.Inch:
                    return value / 63360;
                case LengthUnit.Kilometer:
                    return value / 1.609344;
                case LengthUnit.Yard:
                    return value / 1760;
                case LengthUnit.Meter:
                    return value / 1609.344;
                case LengthUnit.Foot:
                    return value / 5280;
                default:
                    throw new NotSupportedException($"Unsupported length unit: {lengthUnit}");
            }
        }

        /// <summary>
        /// 将长度值转换为英尺
        /// </summary>
        public double ConvertToFoot(double value, LengthUnit lengthUnit)
        {
            // 根据长度单位进行转换
            switch (lengthUnit)
            {
                case LengthUnit.Foot:
                    return value;
                case LengthUnit.Meter:
                    return value / 0.3048;
                case LengthUnit.Centimeter:
                    return value / 30.48;
                case LengthUnit.Mile:
                    return value * 5280;
                case LengthUnit.Kilometer:
                    return value * 3280.84;
                case LengthUnit.Yard:
                    return value * 3;
                case LengthUnit.Inch:
                    return value * 12;
                default:
                    throw new NotSupportedException($"Unsupported length unit: {lengthUnit}");
            }
        }

        /// <summary>
        /// 将长度值转换为厘米
        /// </summary>
        public double ConvertToCentimeter(double value, LengthUnit lengthUnit)
        {
            // 根据长度单位进行转换
            switch (lengthUnit)
            {
                case LengthUnit.Centimeter:
                    return value;
                case LengthUnit.Meter:
                    return value * 100;
                case LengthUnit.Inch:
                    return value * 2.54;
                case LengthUnit.Mile:
                    return value * 160934.4;
                case LengthUnit.Kilometer:
                    return value * 100000;
                case LengthUnit.Yard:
                    return value * 91.44;
                case LengthUnit.Foot:
                    return value * 30.48;
                default:
                    throw new NotSupportedException($"Unsupported length unit: {lengthUnit}");
            }
        }

        /// <summary>
        /// 将长度值转换为千米
        /// </summary>
        public double ConvertToKilometer(double value, LengthUnit lengthUnit)
        {
            // 根据长度单位进行转换
            switch (lengthUnit)
            {
                case LengthUnit.Meter:
                    return value / 1000;
                case LengthUnit.Inch:
                    return value / 39370.1;
                case LengthUnit.Mile:
                    return value / 1.609344;
                case LengthUnit.Yard:
                    return value / 1093.6133;
                case LengthUnit.Foot:
                    return value / 3280.8399;
                case LengthUnit.Kilometer:
                    return value;
                case LengthUnit.Centimeter:
                    return value / 100000;
                default:
                    throw new NotSupportedException($"Unsupported length unit: {lengthUnit}");
            }
        }

        /// <summary>
        /// 将重量值转换为克
        /// </summary>
        public double ConvertToGram(double value, WeightUnit weightUnit)
        {
            // 根据重量单位进行转换
            switch (weightUnit)
            {
                case WeightUnit.Gram:
                    return value;
                case WeightUnit.Kilogram:
                    return value * 1000;
                case WeightUnit.Pound:
                    return value * 453.59237;
                case WeightUnit.Tonne:
                    return value * 1000000;
                case WeightUnit.Ounce:
                    return value * 28.349523125;
                case WeightUnit.Milligram:
                    return value / 1000;
                default:
                    throw new NotSupportedException($"Unsupported weight unit: {weightUnit}");
            }
        }

        /// <summary>
        /// 将重量值转换为千克
        /// </summary>
        public double ConvertToKilogram(double value, WeightUnit weightUnit)
        {
            // 根据重量单位进行转换
            switch (weightUnit)
            {
                case WeightUnit.Kilogram:
                    return value;
                case WeightUnit.Gram:
                    return value / 1000;
                case WeightUnit.Pound:
                    return value * 0.45359237;
                case WeightUnit.Tonne:
                    return value * 1000;
                case WeightUnit.Ounce:
                    return value * 0.028349523125;
                case WeightUnit.Milligram:
                    return value / 1000000;
                default:
                    throw new NotSupportedException($"Unsupported weight unit: {weightUnit}");
            }
        }

        /// <summary>
        /// 将功率值转换为瓦特
        /// </summary>
        public double ConvertToWatt(double value, PowerUnit powerUnit)
        {
            // 根据功率单位进行转换
            switch (powerUnit)
            {
                case PowerUnit.Watt:
                    return value;
                case PowerUnit.Kilowatt:
                    return value * 1000;
                case PowerUnit.Horsepower:
                    return value * 745.699872;
                case PowerUnit.Megawatt:
                    return value * 1000000;
                default:
                    throw new NotSupportedException($"Unsupported power unit: {powerUnit}");
            }
        }

        /// <summary>
        /// 将电流值转换为安培
        /// </summary>
        public double ConvertToAmpere(double value, CurrentUnit currentUnit)
        {
            // 根据电流单位进行转换
            switch (currentUnit)
            {
                case CurrentUnit.Ampere:
                    return value;
                case CurrentUnit.Milliampere:
                    return value / 1000;
                case CurrentUnit.Microampere:
                    return value / 1000000;
                case CurrentUnit.Kiloampere:
                    return value * 1000;
                default:
                    throw new NotSupportedException($"Unsupported current unit: {currentUnit}");
            }
        }

        /// <summary>
        /// 将电压值转换为伏特
        /// </summary>
        public double ConvertToVolt(double value, VoltageUnit voltageUnit)
        {
            // 根据电压单位进行转换
            switch (voltageUnit)
            {
                case VoltageUnit.Volt:
                    return value;
                case VoltageUnit.Millivolt:
                    return value / 1000;
                case VoltageUnit.Microvolt:
                    return value / 1000000;
                case VoltageUnit.Kilovolt:
                    return value * 1000;
                default:
                    throw new NotSupportedException($"Unsupported voltage unit: {voltageUnit}");
            }
        }
    }
复制代码

3. 生成单元测试代码

首先选择整个类,然后输入以下Prompt

@workspace /tests  请对选中的代码,使用MSTest单元测试框架,生成单元测试代码,请为每个方法都实现单元测试

 

 每次仅生成了一个方法的单元测试,可以继续使用以下Prompt

Repeat similar tests for other methods:ConvertToMile, ConvertToFoot, ConvertToCentimeter, ConvertToKilometer, ConvertToGram, ConvertToKilogram, ConvertToWatt, ConvertToAmpere, ConvertToVolt

最终生成的UnitTest代码

复制代码
using Microsoft.VisualStudio.TestTools.UnitTesting;
using T.Core.i10n.Service;
using T.Core.i10n.SPI;

namespace T.Core.i10n.Service.Tests
{
    [TestClass]
    public class MeasurementServiceTests
    {
        private MeasurementService? _measurementService;

        [TestInitialize]
        public void Setup()
        {
            _measurementService = new MeasurementService();
        }

        [TestMethod]
        public void ConvertToInch_ShouldConvertCorrectly()
        {
            var result = _measurementService!.ConvertToInch(1, LengthUnit.Meter);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(39.3701, result, 0.0001);
        }

        [TestMethod]
        [ExpectedException(typeof(NotSupportedException))]
        public void ConvertToInch_ShouldThrowExceptionForUnsupportedUnit()
        {
            _measurementService!.ConvertToInch(1, (LengthUnit)999);
        }

        [TestMethod]
        public void ConvertToMile_ShouldConvertCorrectly()
        {
            var result = _measurementService!.ConvertToMile(1, LengthUnit.Kilometer);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(0.621371, result, 0.0001);
        }

        [TestMethod]
        [ExpectedException(typeof(NotSupportedException))]
        public void ConvertToMile_ShouldThrowExceptionForUnsupportedUnit()
        {
            _measurementService!.ConvertToMile(1, (LengthUnit)999);
        }

        [TestMethod]
        public void ConvertToFoot_ShouldConvertCorrectly()
        {
            var result = _measurementService!.ConvertToFoot(1, LengthUnit.Meter);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(3.28084, result, 0.0001);
        }

        [TestMethod]
        [ExpectedException(typeof(NotSupportedException))]
        public void ConvertToFoot_ShouldThrowExceptionForUnsupportedUnit()
        {
            _measurementService!.ConvertToFoot(1, (LengthUnit)999);
        }

        [TestMethod]
        public void ConvertToCentimeter_ShouldConvertCorrectly()
        {
            var result = _measurementService!.ConvertToCentimeter(1, LengthUnit.Meter);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(100, result, 0.0001);
        }

        [TestMethod]
        [ExpectedException(typeof(NotSupportedException))]
        public void ConvertToCentimeter_ShouldThrowExceptionForUnsupportedUnit()
        {
            _measurementService!.ConvertToCentimeter(1, (LengthUnit)999);
        }

        [TestMethod]
        public void ConvertToKilometer_ShouldConvertCorrectly()
        {
            var result = _measurementService!.ConvertToKilometer(1, LengthUnit.Meter);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(0.001, result, 0.0001);
        }

        [TestMethod]
        [ExpectedException(typeof(NotSupportedException))]
        public void ConvertToKilometer_ShouldThrowExceptionForUnsupportedUnit()
        {
            _measurementService!.ConvertToKilometer(1, (LengthUnit)999);
        }

        [TestMethod]
        public void ConvertToGram_ShouldConvertCorrectly()
        {
            var result = _measurementService!.ConvertToGram(1, WeightUnit.Kilogram);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(1000, result, 0.0001);
        }

        [TestMethod]
        [ExpectedException(typeof(NotSupportedException))]
        public void ConvertToGram_ShouldThrowExceptionForUnsupportedUnit()
        {
            _measurementService!.ConvertToGram(1, (WeightUnit)999);
        }

        [TestMethod]
        public void ConvertToKilogram_ShouldConvertCorrectly()
        {
            var result = _measurementService!.ConvertToKilogram(1, WeightUnit.Gram);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(0.001, result, 0.0001);
        }

        [TestMethod]
        [ExpectedException(typeof(NotSupportedException))]
        public void ConvertToKilogram_ShouldThrowExceptionForUnsupportedUnit()
        {
            _measurementService!.ConvertToKilogram(1, (WeightUnit)999);
        }

        [TestMethod]
        public void ConvertToWatt_ShouldConvertCorrectly()
        {
            var result = _measurementService!.ConvertToWatt(1, PowerUnit.Kilowatt);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(1000, result, 0.0001);
        }

        [TestMethod]
        [ExpectedException(typeof(NotSupportedException))]
        public void ConvertToWatt_ShouldThrowExceptionForUnsupportedUnit()
        {
            _measurementService!.ConvertToWatt(1, (PowerUnit)999);
        }

        [TestMethod]
        public void ConvertToAmpere_ShouldConvertCorrectly()
        {
            var result = _measurementService!.ConvertToAmpere(1, CurrentUnit.Milliampere);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(0.001, result, 0.0001);
        }

        [TestMethod]
        [ExpectedException(typeof(NotSupportedException))]
        public void ConvertToAmpere_ShouldThrowExceptionForUnsupportedUnit()
        {
            _measurementService!.ConvertToAmpere(1, (CurrentUnit)999);
        }

        [TestMethod]
        public void ConvertToVolt_ShouldConvertCorrectly()
        {
            var result = _measurementService!.ConvertToVolt(1, VoltageUnit.Millivolt);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(0.001, result, 0.0001);
        }

        [TestMethod]
        [ExpectedException(typeof(NotSupportedException))]
        public void ConvertToVolt_ShouldThrowExceptionForUnsupportedUnit()
        {
            _measurementService!.ConvertToVolt(1, (VoltageUnit)999);
        }
        [TestMethod]
        public void ConvertToInch_ShouldConvertCorrectly_ForEachLengthUnit()
        {
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(1, _measurementService!.ConvertToInch(1, LengthUnit.Inch), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(39.3701, _measurementService!.ConvertToInch(1, LengthUnit.Meter), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(0.393701, _measurementService!.ConvertToInch(1, LengthUnit.Centimeter), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(39370.1, _measurementService!.ConvertToInch(1, LengthUnit.Kilometer), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(63360, _measurementService!.ConvertToInch(1, LengthUnit.Mile), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(12, _measurementService!.ConvertToInch(1, LengthUnit.Foot), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(36, _measurementService!.ConvertToInch(1, LengthUnit.Yard), 0.0001);
        }

        [TestMethod]
        public void ConvertToMile_ShouldConvertCorrectly_ForEachLengthUnit()
        {
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(1, _measurementService!.ConvertToMile(1, LengthUnit.Mile), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(0.0000062137, _measurementService!.ConvertToMile(1, LengthUnit.Centimeter), 0.0000000001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(0.0000157828, _measurementService!.ConvertToMile(1, LengthUnit.Inch), 0.0000000001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(0.621371, _measurementService!.ConvertToMile(1, LengthUnit.Kilometer), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(0.0005681818, _measurementService!.ConvertToMile(1, LengthUnit.Yard), 0.0000000001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(0.0006213712, _measurementService!.ConvertToMile(1, LengthUnit.Meter), 0.0000000001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(0.0001893939, _measurementService!.ConvertToMile(1, LengthUnit.Foot), 0.0000000001);
        }

        [TestMethod]
        public void ConvertToFoot_ShouldConvertCorrectly_ForEachLengthUnit()
        {
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(1, _measurementService!.ConvertToFoot(1, LengthUnit.Foot), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(3.28084, _measurementService!.ConvertToFoot(1, LengthUnit.Meter), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(0.0328084, _measurementService!.ConvertToFoot(1, LengthUnit.Centimeter), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(3280.84, _measurementService!.ConvertToFoot(1, LengthUnit.Kilometer), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(5280, _measurementService!.ConvertToFoot(1, LengthUnit.Mile), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(3, _measurementService!.ConvertToFoot(1, LengthUnit.Yard), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(0.0833333, _measurementService!.ConvertToFoot(1, LengthUnit.Inch), 0.0001);
        }

        [TestMethod]
        public void ConvertToCentimeter_ShouldConvertCorrectly_ForEachLengthUnit()
        {
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(1, _measurementService!.ConvertToCentimeter(1, LengthUnit.Centimeter), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(100, _measurementService!.ConvertToCentimeter(1, LengthUnit.Meter), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(2.54, _measurementService!.ConvertToCentimeter(1, LengthUnit.Inch), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(100000, _measurementService!.ConvertToCentimeter(1, LengthUnit.Kilometer), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(160934.4, _measurementService!.ConvertToCentimeter(1, LengthUnit.Mile), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(91.44, _measurementService!.ConvertToCentimeter(1, LengthUnit.Yard), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(30.48, _measurementService!.ConvertToCentimeter(1, LengthUnit.Foot), 0.0001);
        }

        // Continue with similar tests for the other methods...
        [TestMethod]
        public void ConvertToKilometer_ShouldConvertCorrectly_ForEachLengthUnit()
        {
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(1, _measurementService!.ConvertToKilometer(1, LengthUnit.Kilometer), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(0.001, _measurementService!.ConvertToKilometer(1, LengthUnit.Meter), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(0.0000254, _measurementService!.ConvertToKilometer(1, LengthUnit.Inch), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(1.609344, _measurementService!.ConvertToKilometer(1, LengthUnit.Mile), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(0.0009144, _measurementService!.ConvertToKilometer(1, LengthUnit.Yard), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(0.0003048, _measurementService!.ConvertToKilometer(1, LengthUnit.Foot), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(0.00001, _measurementService!.ConvertToKilometer(1, LengthUnit.Centimeter), 0.0001);
        }

        [TestMethod]
        public void ConvertToGram_ShouldConvertCorrectly_ForEachWeightUnit()
        {
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(1, _measurementService!.ConvertToGram(1, WeightUnit.Gram), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(1000, _measurementService!.ConvertToGram(1, WeightUnit.Kilogram), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(453.59237, _measurementService!.ConvertToGram(1, WeightUnit.Pound), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(1000000, _measurementService!.ConvertToGram(1, WeightUnit.Tonne), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(28.349523125, _measurementService!.ConvertToGram(1, WeightUnit.Ounce), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(0.001, _measurementService!.ConvertToGram(1, WeightUnit.Milligram), 0.0001);
        }        

        [TestMethod]
        public void ConvertToKilogram_ShouldConvertCorrectly_ForEachWeightUnit()
        {
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(1, _measurementService!.ConvertToKilogram(1, WeightUnit.Kilogram), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(0.001, _measurementService!.ConvertToKilogram(1, WeightUnit.Gram), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(0.453592, _measurementService!.ConvertToKilogram(1, WeightUnit.Pound), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(1000, _measurementService!.ConvertToKilogram(1, WeightUnit.Tonne), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(0.0283495, _measurementService!.ConvertToKilogram(1, WeightUnit.Ounce), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(0.000001, _measurementService!.ConvertToKilogram(1, WeightUnit.Milligram), 0.0001);
        }

        [TestMethod]
        public void ConvertToWatt_ShouldConvertCorrectly_ForEachPowerUnit()
        {
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(1, _measurementService!.ConvertToWatt(1, PowerUnit.Watt), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(1000, _measurementService!.ConvertToWatt(1, PowerUnit.Kilowatt), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(745.7, _measurementService!.ConvertToWatt(1, PowerUnit.Horsepower), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(1000000, _measurementService!.ConvertToWatt(1, PowerUnit.Megawatt), 0.0001);
        }

        [TestMethod]
        public void ConvertToAmpere_ShouldConvertCorrectly_ForEachCurrentUnit()
        {
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(1, _measurementService!.ConvertToAmpere(1, CurrentUnit.Ampere), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(0.001, _measurementService!.ConvertToAmpere(1, CurrentUnit.Milliampere), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(0.000001, _measurementService!.ConvertToAmpere(1, CurrentUnit.Microampere), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(1000, _measurementService!.ConvertToAmpere(1, CurrentUnit.Kiloampere), 0.0001);
        }

        [TestMethod]
        public void ConvertToVolt_ShouldConvertCorrectly_ForEachVoltageUnit()
        {
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(1, _measurementService!.ConvertToVolt(1, VoltageUnit.Volt), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(0.001, _measurementService!.ConvertToVolt(1, VoltageUnit.Millivolt), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(0.000001, _measurementService!.ConvertToVolt(1, VoltageUnit.Microvolt), 0.0001);
            Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreEqual(1000, _measurementService!.ConvertToVolt(1, VoltageUnit.Kilovolt), 0.0001);
        }

        // Continue with similar tests for the other methods...
    }
}
复制代码

以上单元测试代码,直接在VS Code 右键Run Test即可。

 

 

周国庆

2023/11/5

 

 
分类: LLM / ChatGPT , LLM