c# - 输出是另一个输入的单元测试方法

标签 c# unit-testing

我总是尝试在每个测试中坚持一个断言,但有时我在这样做时遇到麻烦。

例如。

假设我编写了一个加密和解密字符串的加密类。

public class CryptoDummy
{
    public string Decrypt(string value)
    {
    }

    public string Encrypt(string value)
    {
    }
}

如果解密取决于加密的输出,我将如何创建我的单元测试?

到目前为止,我的大部分测试(如果不是全部的话)都是由每个测试一个方法调用和每个测试一个断言组成。

因此,对于每个测试进行多次调用并断言我上次调用的方法所产生的最终结果是否合适?

public class CryptoDummyTest
{
    private static CryptoDummy _cryptoDummy;

    // Use ClassInitialize to run code before running the first test in the class
    [ClassInitialize]
    public static void MyClassInitialize(TestContext testContext)
    {
        _cryptoDummy = new CryptoDummy();
    }

    [TestMethod]
    public void Encrypt_should_return_ciphered_64string_when_passing_a_plaintext_value()
    {
        const string PLAINTEXT_VALUE = "anonymous@provider.com";

        string cipheredString = _cryptoDummy.Encrypt(PLAINTEXT_VALUE);

        Assert.IsTrue(cipheredString != PLAINTEXT_VALUE);
    }

    [TestMethod]
    public void Decrypt_should_return_plaintext_when_passing_a_ciphered_value()
    {
        const string PLAINTEXT_VALUE = "anonymous@provider.com";

        string cipheredString = _cryptoDummy.Encrypt(PLAINTEXT_VALUE);

        string plaintextString = _cryptoDummy.Decrypt(cipheredString);

        Assert.IsTrue(plaintextString == PLAINTEXT_VALUE);
    }
}

提前谢谢你。

最佳答案

你不应该让一个测试依赖于另一个测试。最好的方法是将加密文本输出到某处并保存。然后在解密文本测试中,您可以从加密文本开始并测试您是否正确解密它。如果您使用相同的加密 key (这对测试很好),加密的字符串将始终相同。因此,将您的第二个单元测试更改为如下内容:

[TestMethod]
public void Decrypt_should_return_plaintext_when_passing_a_ciphered_value()
{

    const string PLAINTEXT_VALUE = "anonymous@provider.com";

    string cipheredString = "sjkalsdfjasdljs"; // ciphered value captured

    string plaintextString = _cryptoDummy.Decrypt(cipheredString);

    Assert.IsTrue(plaintextString == PLAINTEXT_VALUE);
}

关于c# - 输出是另一个输入的单元测试方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7848328/

相关文章:

c# - 如何编写本地化的屏幕键盘

c# - 寻找 C# 代码解析器

java - 用于查找数组中最大数量的参数化 Junit 测试用例的预期值

c# - 在编写单元测试时断言 "nothing happened"

php - magento paypal 收到错误 :We're sorry, PayPal 不允许美国居民将购买的商品运送到英国

c# - 错误: Fatal error encountered attempting to read the resultset

c# - Blazor - 参数值的组件 "intellisense"

c# - 代码无法识别 xaml 中的名称 View (Xamarin Forms Visual Studio 2015)

javascript - 使用 Jest ("Cannot read property ' __extends' of null 进行单元测试 typescript 类”)

ruby-on-rails - 代码有可能在 Git 不知情的情况下更改吗?