简体   繁体   English

单元测试实用程序方法

[英]Unit Testing Utility Methods

If I have a utility method such as below, how am I supposed to unit test it? 如果我有如下所示的实用程序方法,应该如何对其进行单元测试? It seems like if I wanted to determine that the output was correct I would have to build the code into the test method? 似乎如果我想确定输出正确,就必须将代码构建到测试方法中吗? I could see if there was conditional logic such as if the input string is empty return null, but testing for correct output seems tricky. 我可以看到是否存在条件逻辑,例如输入字符串为空,则返回null,但是测试正确的输出似乎很棘手。

public static string EncodeTo64(string input)
{
    byte[] b = System.Text.ASCIIEncoding.ASCII.GetBytes(input);
    string returnValue = System.Convert.ToBase64String(b);
    return returnValue;
}

I would test it by inputting a value I knew the correct output from. 我将通过输入一个我知道正确输出的值来进行测试。 Either by calculating it beforehand, or by comparing it to a known value. 可以通过预先计算,也可以将其与已知值进行比较。 You are probably able to compute the output for a short string yourself. 您可能可以自己计算一个短字符串的输出。

Further I would test the methods behavior for border conditions like null values and empty strings. 此外,我将测试边界条件(例如空值和空字符串)的方法行为。

It depends on what the meaning of "correctness" for this function is to you, the developer. 这取决于开发人员对您而言此功能的“正确性”的含义。 I would convert a known string to the output, verify that that is correct according to whatever criteria matters to me, and then compare that the result of the function matches the result I've produced. 我会将已知的字符串转换为输出,根据对我而言重要的条件验证该字符串是否正确,然后比较该函数的结果是否与我生成的结果相匹配。 Something like this: 像这样:

const string expectedBase64String = "abc123$$%++";
const string testString = "Not the base 64 source of above";

Assert.AreEqual(expected, Utility.EncodeTo64(testString));

You are correct essentially...you'll need to rely on some other definition of correctness other than the behavior of your code, unless all you need to test is "this is still producing what it did the first time I ran it". 本质上来说,您是正确的……除了代码的行为外,您还需要依赖其他一些正确性定义,除非您需要测试的仅仅是“这仍然会产生我第一次运行它时所做的事情”。

With a few exceptions, you wouldn't test the output at all, because that's implemented by another unit - the System.Convert class, and it's already well-tested. 除少数例外,您根本不会测试输出,因为它是由另一个单元System.Convert类实现的,并且已经过了很好的测试。

It would make sense to to write tests that document what the method does when you pass it unusual inputs: null, string.Empty , strings with non-ASCII encodings, etc.. 编写测试记录该方法在传递异常输入时执行的操作是很有意义的:null, string.Empty ,具有非ASCII编码的字符串等。

Use pre-determined input and the resulting correct output and compare against what your method produces. 使用预定输入和正确的输出结果,并与您的方法产生的结果进行比较。 Do this for several input/output pairs to test the overall correctness of your method. 对几个输入/输出对执行此操作,以测试方法的整体正确性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM