【问题标题】:How do I "Unit Test" in C#? [closed]如何在 C# 中“单元测试”? [关闭]
【发布时间】:2016-04-16 00:28:48
【问题描述】:

所以我的项目中有这个方法:

public static String MD5Hash(string TextToHash)
{
    if ((TextToHash == null) || (TextToHash.Length == 0))
    {
        return String.Empty;
    }

    MD5 md5 = new MD5CryptoServiceProvider();
    byte[] textToHash = Encoding.Default.GetBytes(TextToHash);
    byte[] result = md5.ComputeHash(textToHash);
    return System.BitConverter.ToString(result);

}

我已经尝试过这样的测试:

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using BugMon;

namespace BugMonTesting
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            string pwd = "Password";
            string expected = "DC-64-7E-B6-5E-67-11-E1-55-37-52-18-21-2B-39-64";
            frmLogIn.MD5Hash(pwd);
            Assert.AreEqual(pwd, expected);
        }
    }
}

但是当我运行测试并保持为“密码”时,字符串 pwd 似乎没有通过方法。

我做错了什么?

很抱歉,如果这很明显,但我以前从未使用过这些测试。

【问题讨论】:

标签: c# visual-studio unit-testing testing


【解决方案1】:

你永远不会对 MD5Hash 的返回值做任何事情。

试试这个:

string hash = frmLogIn.MD5Hash(pwd);
Assert.AreEqual(hash, expected);

请注意,这仅在 MD5Hash 返回格式类似于 expected 变量的字符串时才有效。

【讨论】:

  • 甜蜜!立即工作,太简单了,我没注意到...谢谢!
  • 请不要建议人们用新值覆盖现有变量。这是一种非常糟糕的编码风格。
  • @DavidArno,说得好。
  • 谢谢大家,现在将其更改为将散列值存储在一个新的未使用变量中
猜你喜欢
  • 2011-01-03
  • 1970-01-01
  • 2019-02-15
  • 2014-03-20
  • 1970-01-01
  • 2010-09-09
  • 1970-01-01
  • 1970-01-01
  • 2011-02-14
相关资源
最近更新 更多