单元测试有哪些流行的命名约定?

发布于 2024-07-04 15:00:33 字数 781 浏览 11 评论 0原文

一般

  • 要求 所有测试均遵循相同的标准。
  • 清楚每个测试状态是什么。
  • 具体说明预期的行为。

示例

1) MethodName_StateUnderTest_ExpectedBehavior

Public void Sum_NegativeNumberAs1stParam_ExceptionThrown() 

Public void Sum_NegativeNumberAs2ndParam_ExceptionThrown () 

Public void Sum_simpleValues_Calculated ()

来源:单元测试的命名标准

2) 用下划线分隔每个单词

Public void Sum_Negative_Number_As_1st_Param_Exception_Thrown() 

Public void Sum_Negative_Number_As_2nd_Param_Exception_Thrown () 

Public void Sum_Simple_Values_Calculated ()

其他

  • 结束方法名称以 Test
  • 开始方法名称以类名称

General

  • Follow the same standards for all tests.
  • Be clear about what each test state is.
  • Be specific about the expected behavior.

Examples

1) MethodName_StateUnderTest_ExpectedBehavior

Public void Sum_NegativeNumberAs1stParam_ExceptionThrown() 

Public void Sum_NegativeNumberAs2ndParam_ExceptionThrown () 

Public void Sum_simpleValues_Calculated ()

Source: Naming standards for Unit Tests

2) Separating Each Word By Underscore

Public void Sum_Negative_Number_As_1st_Param_Exception_Thrown() 

Public void Sum_Negative_Number_As_2nd_Param_Exception_Thrown () 

Public void Sum_Simple_Values_Calculated ()

Other

  • End method names with Test
  • Start method names with class name

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

哀由 2024-07-11 15:00:33

我对测试命名空间、类和方法使用“T”前缀。

我尝试简洁地创建复制命名空间的文件夹,然后为测试创建一个测试文件夹或单独的项目,并为基本测试复制生产结构:

AProj
   Objects
      AnObj
         AProp
   Misc
      Functions
         AFunc
   Tests
      TObjects
         TAnObj
            TAnObjsAreEqualUnderCondition
      TMisc
         TFunctions
            TFuncBehavesUnderCondition

我可以轻松地看到某个东西是测试,我确切地知道原始代码是什么它涉及(如果你不能解决这个问题,那么无论如何测试都太复杂了)。

它看起来就像接口命名约定(我的意思是,您不会与以“I”开头的事物混淆,也不会与“T”开头的事物混淆)。

无论是否进行测试,编译都很容易。

无论如何,它在理论上是很好的,并且对于小型项目来说效果很好。

I use a 'T' prefix for test namespaces, classes and methods.

I try to be neat and create folders that replicate the namespaces, then create a tests folder or separate project for the tests and replicate the production structure for the basic tests:

AProj
   Objects
      AnObj
         AProp
   Misc
      Functions
         AFunc
   Tests
      TObjects
         TAnObj
            TAnObjsAreEqualUnderCondition
      TMisc
         TFunctions
            TFuncBehavesUnderCondition

I can easily see that something is a test, I know exactly what original code it pertains to, (if you can't work that out, then the test is too convoluted anyway).

It looks just like the interfaces naming convention, (I mean, you don't get confused with things starting with 'I', nor will you with 'T').

It's easy to just compile with or without the tests.

It's good in theory anyway, and works pretty well for small projects.

你在我安 2024-07-11 15:00:33

第一组名称对我来说更易读,因为驼峰式分隔单词,下划线分隔命名方案的各个部分。

我还倾向于在某个地方包含“Test”,无论是在函数名称中还是在封闭的命名空间或类中。

The first set of names is more readable to me, since the CamelCasing separates words and the underbars separate parts of the naming scheme.

I also tend to include "Test" somewhere, either in the function name or the enclosing namespace or class.

眼中杀气 2024-07-11 15:00:33

只要你遵循单一的练习,这并不重要。 一般来说,我为一个方法编写一个单元测试,该测试涵盖了一个方法的所有变体(我有简单的方法;),然后为需要它的方法编写更复杂的测试集。 因此,我的命名结构通常是测试的(JUnit 3 的保留)。

As long as you follow a single practice, it doesn't really matter. Generally, I write a single unit test for a method that covers all the variations for a method (I have simple methods;) and then write more complex sets of tests for methods that require it. My naming structure is thus usually test (a holdover from JUnit 3).

御弟哥哥 2024-07-11 15:00:33

我倾向于使用 MethodName_DoesWhat_WhenTheseConditions 的约定,例如:

Sum_ThrowsException_WhenNegativeNumberAs1stParam

但是,我经常看到的是让测试名称遵循

  • Arrange
  • Act
  • Assert

的单元测试结构,它也遵循 BDD / Gherkin 语法of:

  • Give
  • When
  • Then

将以以下方式命名测试: UnderTheseTestConditions_WhenIDoThis_ThenIGetThis

所以对于您的示例:

WhenNegativeNumberAs1stParam_Sum_ThrowsAnException

但是我更喜欢首先放置要测试的方法名称,因为这样就可以安排测试按字母顺序排列,或在 VisStudio 的成员下拉框中按字母顺序排列,并且 1 种方法的所有测试都分组在一起。


无论如何,我喜欢用下划线分隔测试名称的主要部分,而不是每个单词,因为我认为这样更容易阅读和理解要点的测试跨越。

换句话说,我更喜欢:Sum_ThrowsException_WhenNegativeNumberAs1stParam,而不是Sum_Throws_Exception_When_Negative_Number_As_1st_Param

I tend to use the convention of MethodName_DoesWhat_WhenTheseConditions so for example:

Sum_ThrowsException_WhenNegativeNumberAs1stParam

However, what I do see a lot is to make the test name follow the unit testing structure of

  • Arrange
  • Act
  • Assert

Which also follows the BDD / Gherkin syntax of:

  • Given
  • When
  • Then

which would be to name the test in the manner of: UnderTheseTestConditions_WhenIDoThis_ThenIGetThis

so to your example:

WhenNegativeNumberAs1stParam_Sum_ThrowsAnException

However I do much prefer putting the method name being tested first, because then the tests can be arranged alphabetically, or appear alphabetically sorted in the member dropdown box in VisStudio, and all the tests for 1 method are grouped together.


In any case, I like separating the major sections of the test name with underscores, as opposed to every word, because I think it makes it easier to read and get the point of the test across.

In other words, I like: Sum_ThrowsException_WhenNegativeNumberAs1stParam better than Sum_Throws_Exception_When_Negative_Number_As_1st_Param.

似狗非友 2024-07-11 15:00:33

我非常同意你对这个人的看法。 您使用的命名约定是:

  • 清楚每个测试状态是什么。
  • 具体说明预期的行为。

您还需要测试名称做什么?

Ray 的回答相反,我不认为测试 前缀是必要的。 这是测试代码,我们知道。 如果你需要这样做来识别代码,那么你就会遇到更大的问题,你的测试代码不应该与你的生产代码混淆。

至于下划线的长度和使用,它的测试代码,谁在乎呢? 只有您和您的团队会看到它,只要它可读,并且清楚测试在做什么,就继续吧! :)

也就是说,我对测试仍然很陌生,用它写博客我的冒险 :)

I am pretty much with you on this one man. The naming conventions you have used are:

  • Clear about what each test state is.
  • Specific about the expected behaviour.

What more do you need from a test name?

Contrary to Ray's answer I don't think the Test prefix is necessary. It's test code, we know that. If you need to do this to identify the code, then you have bigger problems, your test code should not be mixed up with your production code.

As for length and use of underscore, its test code, who the hell cares? Only you and your team will see it, so long as it is readable, and clear about what the test is doing, carry on! :)

That said, I am still quite new to testing and blogging my adventures with it :)

那伤。 2024-07-11 15:00:33

这也值得一读:构建单元测试

该结构对于每个被测试的类都有一个测试类。 这并不罕见。 但对我来说不同寻常的是,他为每个被测试的方法都有一个嵌套类。

例如

using Xunit;

public class TitleizerFacts
{
    public class TheTitleizerMethod
    {
        [Fact]
        public void NullName_ReturnsDefaultTitle()
        {
            // Test code
        }

        [Fact]
        public void Name_AppendsTitle()
        {
            // Test code
        }
    }

    public class TheKnightifyMethod
    {
        [Fact]
        public void NullName_ReturnsDefaultTitle()
        {
            // Test code
        }

        [Fact]
        public void MaleNames_AppendsSir()
        {
            // Test code
        }

        [Fact]
        public void FemaleNames_AppendsDame()
        {
            // Test code
        }
    }
}

,原因如下:

一方面,这是保持测试井井有条的好方法。 一切
方法的测试(或事实)被分组在一起。 例如,如果
您使用 CTRL+M、CTRL+O 快捷键折叠方法体,您可以
轻松扫描您的测试并像阅读代码规范一样阅读它们。

我也喜欢这种方法:

MethodName_StateUnderTest_ExpectedBehavior

所以也许调整为:

StateUnderTest_ExpectedBehavior

因为每个测试都已经在嵌套类中

This is also worth a read: Structuring Unit Tests

The structure has a test class per class being tested. That’s not so unusual. But what was unusual to me was that he had a nested class for each method being tested.

e.g.

using Xunit;

public class TitleizerFacts
{
    public class TheTitleizerMethod
    {
        [Fact]
        public void NullName_ReturnsDefaultTitle()
        {
            // Test code
        }

        [Fact]
        public void Name_AppendsTitle()
        {
            // Test code
        }
    }

    public class TheKnightifyMethod
    {
        [Fact]
        public void NullName_ReturnsDefaultTitle()
        {
            // Test code
        }

        [Fact]
        public void MaleNames_AppendsSir()
        {
            // Test code
        }

        [Fact]
        public void FemaleNames_AppendsDame()
        {
            // Test code
        }
    }
}

And here is why:

Well for one thing, it’s a nice way to keep tests organized. All the
tests (or facts) for a method are grouped together. For example, if
you use the CTRL+M, CTRL+O shortcut to collapse method bodies, you can
easily scan your tests and read them like a spec for your code.

I also like this approach:

MethodName_StateUnderTest_ExpectedBehavior

So perhaps adjust to:

StateUnderTest_ExpectedBehavior

Because each test will already be in a nested class

花海 2024-07-11 15:00:33

我确实像使用“PascalCasing”的其他方法一样命名我的测试方法,没有任何下划线或分隔符。 我保留了该方法的后缀 Test,因为它没有增加任何价值。 该方法是测试方法由属性 TestMethod 指示。

[TestMethod]
public void CanCountAllItems() {
  // Test the total count of items in collection.
}

由于每个测试类只能测试另一个类,因此我将类的名称保留在方法名称之外。 包含测试方法的类的名称类似于被测试的类,带有后缀“Tests”。

[TestClass]
public class SuperCollectionTests(){
    // Any test methods that test the class SuperCollection
}

对于测试异常或不可能的操作的方法,我在测试方法前加上单词Cannot

[TestMethod]
[ExpectedException(typeOf(ArgumentException))]
public void CannotAddSameObjectAgain() {
  // Cannot add the same object again to the collection.
}

我的命名约定基于文章“TDD提示:测试命名约定”布莱恩·库克的《指南》。 我发现这篇文章非常有帮助。

I do name my test methods like other methods using "PascalCasing" without any underscores or separators. I leave the postfix Test for the method out, cause it adds no value. That the method is a test method is indicated by the attribute TestMethod.

[TestMethod]
public void CanCountAllItems() {
  // Test the total count of items in collection.
}

Due to the fact that each Test class should only test one other class i leave the name of the class out of the method name. The name of the class that contains the test methods is named like the class under test with the postfix "Tests".

[TestClass]
public class SuperCollectionTests(){
    // Any test methods that test the class SuperCollection
}

For methods that test for exceptions or actions that are not possible, i prefix the test method with the word Cannot.

[TestMethod]
[ExpectedException(typeOf(ArgumentException))]
public void CannotAddSameObjectAgain() {
  // Cannot add the same object again to the collection.
}

My naming convension are base on the article "TDD Tips: Test Naming Conventions & Guidelines" of Bryan Cook. I found this article very helpful.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文