The definition and function of a unit test

Unit test definition: a unit test is a very important tool in traditional software development, which is to check and verify the smallest unit of testing in software, in general, to verify the correctness of a function in your code. A unit test is an automated code that calls the unit of work that's tested, and then checks for some assumptions about the individual final results of the unit. Unit tests are written using unit test frameworks and require reliable, readable, and. The result of a unit test is stable as long as the product code doesn't change. ( baidu )

A unit test can find bugs in early stages of software development without having to go to integration tests, and develop a module ( class, function ) to perform a unit test. ( unit test is a bar. ). )

Two, using nunit for unit testing in unity

In the course of the work, is very rare to find a unit of unit testing on their own writing functions. In general, after you've developed the function, write two tests ( and even don't test ), and you can't see any problems in the svn or git repository. As a result, the test team will return to a lot of low-level bugs that can be avoided in advance. Of course, they don't have the habit of unit tests, or they don't have to do unit tests because they're too much work, too long, and so on. ( live to don't finish, also do hair test, delay doesn't catch money ). )

All right, it's a free session. It says we've a unit test. The unit test currently has a lot of mature frameworks for us to use, and I recommend that it's the editor run runner that comes with unity editor, but it's. Editor _ test runner is the implementation of the open source unit testing tool nunit in unity engine, which is the version 2. 6. 4 used in unity.

Editor test runner can be opened with the window editor> runner menu, as shown in the following figure:

Display the currently added unit test cases in this window, as well as the case they pass. First, you need to click the run all button in the corner of the window to perform all unit tests. The green pair indicates that the use case is passed by the unit test, and the red symbol indicates that the unit test isn't passed.

Let's look at how to write the code for a unit test. The unit test code and the game runtime code are saved separately, which is available only in the editor environment, so you need to put it in the editor directory.

First of all, we define a custom type error exception for the following test. It's possible to make it directly inherited from an epr, as follows:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

/// <summary>

/// 自定义的异常类型

/// </summary>

class NegativeHealthException : ApplicationException



Here are the modules or code that we need to test. Assuming a player class in the game code represents the actor color, there are several functions used to reduce the amount of blood loss when players are damaged, or. Where the damage function writes three versions, one is correct, two are returning the error results. In the correct function, when the value of health is less than 100, an exception that we just customized is thrown. The code looks like this:

 1 using System.Collections;

 2 using System.Collections.Generic;

 3 using UnityEngine;


 5 public class Player{


 7 public float Health { get; set; }


 9 #region 正确的方法


11 public void Damage(float value)

12  {

13 Health -= value;

14 if (Health <0)

15  {

16 throw new NegativeHealthException();

17  }

18  }


20 public void Recover(float value)

21  {

22 Health += value;

23  }

24 #endregion


26 #region 错误的方法


28 public void DamageWrong(float value)

29  {

30 Health -= value + 1;

31  }


33 public void DamageNoException(float value)

34  {

35 Health -= value;

36  }

37 #endregion

38 }

Then we'll write the unit test code. Here we create a class called PlayerTest that writes two functions that represent two test cases. In order for unity to identify these two functions, we need to add the properties of [ _ test ] before the function, so that all functions with the [ test ] attribute.

 1 using System.Collections;

 2 using System.Collections.Generic;

 3 using NUnit.Framework;

 4 using UnityEngine;


 6 public class PlayerTest{


 8  [Test]

 9 public void TestHealth()

10  {

11 Player player = new Player();

12 player.Health = 1000.0f;


14 //通过Assert断言来判断这个函数的返回结果是否符合预期

15 player.Damage(200);

16 Assert.AreEqual(800,player.Health);


18 player.Recover(150);

19 Assert.AreEqual(950,player.Health);

20  }


22  [Test]

23 [ExpectedException(typeof(NegativeHealthException))]

24 public void NegativeHealth()

25  {

26 Player player = new Player();

27 player.Health = 1000;


29 player.Damage(500);

30 player.Damage(600);

31  }


33 }

When you're writing to [ ExpectedException ( typeof ( negativehealthexception ) ], vs will be warned that the ExpectedException isn't found. This is because ExpectedException is the content of a unit test that belongs to vs, so we also need to use using nunit. Framework; we also need to use nunit. Framework; to introduce the vs 's unit test module. But if you find that the module cannot be introduced, vs doesn't automatically complete this namespace, even if it's manually written or prompted. What's this.

It's well known that unity. Net is based on mono because some reasons cause mono to not contain content in all microsoft native. Net libraries. That's, some of the classes that you use in projects like winform, wpf, and so on aren't perfect in mono, which is why there are modules that don't find unit tests. In fact, this is a good solution, and we can use it in the ide as long as we find the dll for the unit test module in vs ( called microsoft. Visualstudio. QualityTools. UnitTestFramework. Dll ), and then introduce it in the ide. Detailed procedures are as follows:

1. Locate the location of the unit test module dll in vs, which is queried on stackoverflow, we know that microsoft. Visualstudio. QualityTools. UnitTestFramework. Dll is generally in C:Program files ( x86 ) microsoft visual studio 10.0 common7idepublicassembliesmicrosoft. Visualstudio. QualityTools. As shown in the following illustration:

2. Manually copy this dll to the unity project and refer to it in our solution. Create a new folder named plugins in our unity project, and then copy the above microsoft. Visualstudio. QualityTools. UnitTestFramework. Dll to the folder, and then reopen our vs solution, and you can find that the module is automatically referenced, and you can safely use the code.

In traditional c # projects, we're referring to a dll that imports a by a new reference on the reference project of the vs solution, but in the unity project, we find that there's no option on the reference option. In fact, simply copy the dll to the"plugins"directory as described above, vs will automatically reference the dll to our project, very convenient.

In the above test function, if we want to test whether the function is working correctly, you need to use assert. AreEqual to determine whether the return result of this function is consistent with the expected result. If the assert. AreEqual judgment results are correct, the test runner window will be used in a green pair to indicate that the test is in the case of a red. A second negativehealth test case function is used to determine whether the function throws an exception correctly, and if no exception is thrown as expected, it's considered a failed test case. If you need to capture an exception that's consistent with your expected value, you need to add another attribute [ ExpectedException ( typeof ( negativehealthexception ) ) ] before the function. As you can see from the following figure, the two test cases that we've written are passed, showing as green.

At this point, you may find that the above script corresponds to the PlayerTest part of the test results, and there's no playertestwrong grouping. This is because we can add more than one test script in the editor directory, which can test code for the same module, or test code for different modules at the same time. Let's take a look at how playertestwrong 's script is written, its content is very similar to the previous test code, except that the function that returns the error value is called.

 1 using System;

 2 using System.Collections.Generic;

 3 using System.Linq;

 4 using System.Text;

 5 using NUnit.Framework;



 8 class PlayerTestWrong

 9 {

10  [Test]

11 public void TestHealthWrong()

12  {

13 Player player = new Player();

14 player.Health = 1000.0f;


16 player.DamageWrong(200);

17 Assert.AreEqual(800,player.Health);


19 player.DamageWrong(150);

20 Assert.AreEqual(950,player.Health);

21  }


23  [Test]

24 [ExpectedException(typeof (NegativeHealthException))]

25 public void NegativeHealthNoException()

26  {

27 Player player = new Player();

28 player.Health = 1000;


30 player.DamageNoException(500);

31 player.DamageNoException(600);

32  }

33 }

The basic use methods for the editor run runner are introduced here, and a small trick is described below. If you want to implement a fully automated unit test, you might consider using batch to automate testing, which also provides a batch way for unity. If you need to use this feature, just pass in the following parameters when you run unity, the meaning of each parameter is please look at unity official documentation.

  • runEditorTests
  • editorTestsResultFile
  • editorTestsFilter
  • editorTestsCategories
  • editorTestsVerboseLog

Three, summary.

For game developers, unit tests may be strange. However, as the game complexity grows, many companies with a certain scale will develop multiple projects at the same time. We'll find that there are many functions that are encapsulated as generic tools. In this case, if we don't pay attention to the quality of the code, it'll cause a bug to affect the speed of multiple projects at the same time. Therefore, we recommend that you add unit tests to more important modules, as well as reuse of code in time allowed.

Finally, the project source demo demonstrated in this blog:

Github address: https://github. com/XINCGer/Unity3DTraining/tree/master/Unit4Unity/Editor % 20Test % 20Runner welcome.

Reference material:

Https://stackoverflow. com/questions/3293317/where-is-the-microsoft-visualstudio-testtools-unittesting-namespace-on-vs2010.

The author:
Source: http://www. Cnblogs. com/msxh/p/7354229. Html.
Please respect the of others to make sharing a kind of advantage, welcome to copy. In addition, in terms of expression and code, the welcome batch evaluation is positive. Leave your footprint, welcome comments.

Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs