如何断言字符串列表中是否有任何字符串包含在实际字符串中
本文关键字:字符串 任何 包含 是否 列表 何断言 断言 | 更新日期: 2023-09-27 18:36:57
我有以下字符串:
Actual | Expected
"The Actual String" | "The"
| "Actual"
| "String"
| "Other string"
| ...
我需要创建一个方法来Assert
任何Expected
字符串都包含在实际字符串中,如下所示:
[TestClass]
public class UnitTest
{
[TestMethod]
public void TestMethod()
{
//Assertion Passed
AssertContainsString("The Actual String", "The");
//Assertion Passed
AssertContainsString("The Actual String", "Something", "Actual");
//Assertion Failed
AssertContainsString("The Actual String", "Something", "Something Else");
}
public void AssertContainsString(string actual, params string[] expected)
{
}
}
我尝试了CollectionAssert.Contains
方法,但没有奏效。有没有一种快速方法可以在不迭代expected
字符串的情况下使用?
我认为可以在所有Framework .NET中使用这个"StringAssert.Contains(actualString,containsubstring);"
如果在实际变量中找到预期数组的所有值,则返回 true:
bool foundall = expected.Except(actual.Split(' ')).Count()==0;
即使实际字符串中只包含一个值,也返回 true:
bool ans = expected.Except(actual.Split(' ')).Count() != expected.Length;
如果你这样做了
if (actual.Split(' ').Contains(expected)) return true;
但我认为您仍然需要迭代预期的
foreach (string ex in expected)
{
if (actual.Split(' ').Contains(ex)) return true;
}
根据基因S评论编辑
expected.Any(ex => actual.Split(' ').Contains(ex))
如果您愿意,请使用糖,但没有节省处理器成本,它只会使其更难阅读。
字符串类的扩展方法?
public static bool AnyIn(this string s, params string[] values)
{
return values.Any(x => s.Contains(x));
}
可通过以下方式调用:
string test = "The actual string";
if(test.AnyIn("The") == true) // success
...
if(test.AnyIn("The", "actual", "string") == true) // success
...
if(test.AnyIn("The", "actual", "value") == true) // success
...
if(test.AnyIn("some", "value") == true) // fail
或者也
System.Diagnostics.Debug.Assert(test.AnyIn("some", "value"), "No expected string found"); // fail
当然把扩展方法放在一个静态类
中也可在 Visual Studio 2010 控制台应用程序中尝试
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main()
{
string test = "The actual string";
// Prints False
bool result = test.AnyIn("other", "value");
Console.WriteLine(result.ToString());
// Prints True
result = test.AnyIn("other", "The");
Console.WriteLine(result.ToString());
// No Assert dialog here
System.Diagnostics.Debug.Assert(test.AnyIn("other", "The"), "No expected values found");
// Big Assert dialog here with message "No expected values found"
System.Diagnostics.Debug.Assert(test.AnyIn("other", "The"), "No expected values found");
}
}
static class ext
{
public static bool AnyIn(this string s, params string[] values)
{
return values.Any(x => s.Contains(x));
}
}
}
编辑:
可以通过这种方式更改扩展名解决不同情况的问题
public static bool AllIn(this string s, params string[] values)
{
return values.Any(x => s.IndexOf(x + " ", StringComparison.CurrentCultureIgnoreCase) >= 0);
}
但是,为了防止当预期字符串之一嵌入到实际字符串中时出现误报,您需要在实际字符串的末尾添加一个空格
string test = "The actual string "; // notice the extra space added at the end