简体   繁体   English

Assert.AreEqual - 空与空字符串

[英]Assert.AreEqual - Null vs Empty String

Take the following example: 请看以下示例:

string x = null;
var y = String.Empty;
Assert.AreEqual(x, y);             // test fails!
Assert.AreEqual(x ?? "", y ?? ""); // passes, but ugly!

I understand that null and empty string aren't the same but for my particular application these are basically the same. 我知道null和空字符串不一样,但对于我的特定应用程序,这些基本相同。 My question is - are there any shortcuts that will treat null and empty string the same way? 我的问题是 - 是否有任何快捷方式将以同样的方式处理null和空字符串? Otherwise I am faced with using the null coalescing operator all over (a bit ugly!) 否则我面临着全部使用空合并运算符(有点难看!)

Background 背景

For a background on where this question comes from, I'm writing integration tests for a project. 有关此问题来源的背景知识,我正在为项目编写集成测试。 Basically I'm saving values to a database, then loading them again and checking that the two match. 基本上我将值保存到数据库,然后再次加载它们并检查两者是否匹配。 Some values, when saved are empty strings, but when loaded via EF they are coming back as null values. 保存时,某些值是空字符串,但是当通过EF加载时,它们将作为空值返回。 This causes a number of my integration test to fail. 这导致我的一些集成测试失败。

EDIT/NOTE - The values I am using for testing are randomized. 编辑/注意 - 我用于测试的值是随机的。 That means sometimes the value will be empty but other times they will be filled in. That in mind, I would have to use the null coalescent on every single string comparison (hence the question of an abbreviated way of doing this). 这意味着有时值将为空,但有时它们将被填充。记住,我必须在每个字符串比较中使用空合并(因此这是一个缩写方式的问题)。

Drew: AlexD was on track, although he did not have it fully ferreted out. 德鲁:亚历克斯正在走上正轨,尽管他并没有把它完全挖出来。 Example: 例:

    static void Main(string[] args)
    {
        Console.WriteLine(AreSame("", ""));
        Console.WriteLine(AreSame("", null));
        Console.WriteLine(AreSame(null, ""));
        Console.WriteLine(AreSame(null, null));

        Console.Read();
    }

    private static bool AreSame(string x, string y)
    {
        return (string.IsNullOrEmpty(x) == string.IsNullOrEmpty(y));
    }

In your case, you can use 在您的情况下,您可以使用

Assert.AreEqual(string.IsNullOrEmpty(x), string.IsNullOrEmpty(y));

Or 要么

Assert.IsTrue(AreSame(x, y));

Ugly? 丑陋? Sure, but you can at least abstract the ugliness out a bit. 当然,但你至少可以抽出丑陋的一点。 Ugly as 丑陋的

Assert.AreEqual(x ?? "", y ?? ""); // passes, but ugly!

??? ??? Not sure. 不确定。 Depends on how you look at it. 取决于你如何看待它。

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

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