天天看点

初次使用单元测试后的体会

  通过单元测试的类,它的行为是符合当初单元设计的目标的。只要编写单元测试时,从多方面检验类的行为,就能确保在这样的情景下,类是符合设计的。在vistual studio中,最简单的单元测试就是使用本身自带的功能(不需要从网上找nunit的程序集,直接在项目上引用"microsoft.visualstudio.qualitytools.unittestframework"程序集就ok了)。还有另外一个好处,是方便调试。单元测试项目可以在测试运行时,对被测试类下断点,非常节约调试时间。

  我是这么做的,单元测试的代码放到独立的项目中去,引用要测试的项目,在被测试项目中添加assembly特性如下:

  [assembly: internalsvisibleto("projky.unittests")]

  这样,单元测试就能对被测试项目中internal修饰符的类可见,又不破坏程序集的可见性。

  举一个简单的需求,要将如“30d9132169211a45”或者“30-d9-13-21-69-21-1a-45”或者“30 d9 13 21 69 21 1a 45”这样的16进制字符串转换为byte[]数组。设计了一个bytestring的类来实现需求。

internal class bytestring {

public static byte[] convertertobytes(string value) {

if (value.indexof("-") > -1) {

value = value.replace("-", "");

} else if (value.indexof(" ") > -1) {

value = value.replace(" ", "");

}

debug.assert(value.length % 2 == 0, "invalid byte string length.");

list<byte> list = new list<byte>(value.length / 2);

for (int i = 0; i < value.length; i += 2) {

int bhi = getinteger(value[i]);

int blow = getinteger(value[i + 1]);

byte temp = (byte)(bhi << 4 | blow);

list.add(temp);

return list.toarray();

static int getinteger(char ch) {

if (char.isdigit(ch)) {

return ch - '0';

int value = 10;

switch (ch) {

case 'a':

value = 10;

break;

case 'b':

value = 11;

case 'c':

value = 12;

case 'd':

value = 13;

case 'e':

value = 14;

case 'f':

value = 15;

default:

throw new notsupportedexception(ch.tostring() + " is not valid char.");

return value;

 那么,简单验证该类的行为(接口)可以编写下面的测试类:

[testclass]

public class bytestringtest {

[testmethod]

public void convertertobytes() {

string input = "30d9132169211a45";

byte[] bytes = bytestring.convertertobytes(input);

assert.istrue(bytes.length == input.length / 2);

assert.istrue(bytes[0] == 0x30);

assert.istrue(bytes[1] == 0xd9);

assert.istrue(bytes[2] == 0x13);

assert.istrue(bytes[3] == 0x21);

assert.istrue(bytes[4] == 0x69);

assert.istrue(bytes[5] == 0x21);

assert.istrue(bytes[6] == 0x1a);

assert.istrue(bytes[7] == 0x45);

input = "30-d9-13-21-69-21-1a-45";

bytes = bytestring.convertertobytes(input);

assert.istrue(bytes.length == 8);

input = "30 d9 13 21 69 21 1a 45";

  如果单元测试运行失败,例如assert.istrue()方法中,参数为false,则在vs中会抛异常,这样,就知道哪里不正确了。

  注意用[testclass]标记作为单元测试承载的类,是public可见性,而里面单个的独立测试方法,则采用[testmethod]标记,同样是public可见性。

  在visual studio里面还有一个技巧,按ctrl + r,a可以自动运行单元测试项目。如果被测试类有断点的话,测试到该位置时,也会断下来。

最新内容请见作者的github页:http://qaseven.github.io/

继续阅读