没有单元测试的工程就不是好工程, 至少不是大工程. 在 Visual Studio 里可以很方便的进行单元测试的创建和运行. 下面的教程是基于C#但是也可以很容易的应用到其它语言,比如 C++.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | // Example: How to Create Unit Tests // helloacm.com using System; namespace ClassLibrary1 { public class Class1 { public int GetEven() { return new Random().Next()*2; } } } |
// Example: How to Create Unit Tests // helloacm.com using System; namespace ClassLibrary1 { public class Class1 { public int GetEven() { return new Random().Next()*2; } } }
在这个简单的类里, 我们有一个方法 GetEven() 用来返回随机的一个偶数, 我们可以通过新工程向导, 来创建一个测试工程.
我们需要在同一的项目树里把两个工程都包括进来 (这样就可以方便项目之间进行引用).
我们接着需要完成 [UnitTest1.cs], 把 TestMethod1 测试代码填完整:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | using ClassLibrary1; using Microsoft.VisualStudio.TestTools.UnitTesting; // Example: How to Create Unit Tests // helloacm.com namespace UnitTestProject1 { [TestClass] public class UnitTest1 { [TestMethod] public void TestMethod1() { Assert.IsTrue(new Class1().GetEven() % 2 == 0); } } } |
using ClassLibrary1; using Microsoft.VisualStudio.TestTools.UnitTesting; // Example: How to Create Unit Tests // helloacm.com namespace UnitTestProject1 { [TestClass] public class UnitTest1 { [TestMethod] public void TestMethod1() { Assert.IsTrue(new Class1().GetEven() % 2 == 0); } } }
当然, 我们需要在 [UnitTestProject1] 里添加对 [ClassLibrary1] 的引用, using ClassLibrary1. 然后我们就可以通过断言 Assert来检查GetEven 方法是否返回偶数(这个需要开发人员自己写).
然后在 Visual Studio 的菜单选择 “Test” — “Run” — “All Tests” or (Ctrl + R, A) 这样就会自动寻找所有测试用例并进行测试.
为了说明, 我们把 Assert 的判断逻辑改反:
Assert.IsTrue(new Class1().GetEven() % 2 == 1);
重新进行单元测试, 这样可以看到系统说失败:
Resharper 插件有一个功能更加多的单元测试窗口:
当然, 可以通过命令行 mstest.exe 在 Continuous Integration 服务器上对所编译的代码进行单元测试:
mstest.exe /testcontainer:UnitTestProject1.dll /resultsfile:res.trx
英文同步: https://helloacm.com/how-to-create-and-run-unit-tests-in-c-net-a-quick-tutorial/
GD Star Rating
loading...
本文一共 322 个汉字, 你数一下对不对.loading...
上一篇: USB充电速度影响因素
下一篇: 舍得给员工培训的公司是好公司
扫描二维码,分享本文到微信朋友圈
