那么,简单验证该类的行为(接口)可以编写下面的测试类:
[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); 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); 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); } } |
如果单元测试运行失败,例如Assert.IsTrue()方法中,参数为False,则在VS中会抛异常,这样,就知道哪里不正确了。
注意用[TestClass]标记作为单元测试承载的类,是public可见性,而里面单个的独立测试方法,则采用[TestMethod]标记,同样是public可见性。
在Visual Studio里面还有一个技巧,按Ctrl + R,A可以自动运行单元测试项目。如果被测试类有断点的话,测试到该位置时,也会断下来。