如何正确格式化NUnit 3自定义约束输出

时间:2018-11-06 13:58:39

标签: constraints nunit-3.0

我正在尝试创建自己的自定义“文件存在断言”,其中错误消息提供的信息比

               Test result message:   File not found
               Expected: file exists
               But was:  "C:\folder\myFileName.msi"

我想写点类似的东西

               Test result message:   File not found
               Expected: myFileName.msi to exist in C:\folder
               But was:  anotherFile.msi otherFile.msi randomFile.msi

我可以通过重写约束中的Description来获取信息,但是最终错误消息的格式不正确。

                Test result message:   Expected: File not found
                Expected: 18a.txt to exist in C:\folder
                But was: C:\folder\abcd.txt C:\folder\ABCDEFGHIJKLMNOPQRSTUVWXYZ - Copy (10).txt C:\folder\ABCDEFGHIJKLMNOPQRSTUVWXYZ - Copy (11).txt C:\folder\ABCDEFGHIJKLMNOPQRSTUVWXYZ - Copy (12).txt C:\folder\ABCDEFGHIJKLMNOPQRSTUVWXYZ - Copy (13).txt C:\folder\ABCDEFGHIJKLMNOPQRSTUVWXYZ - Copy (14).txt C:\folder\ABCDEFGHIJKLMNOPQRSTUVWXYZ.txt C:\folder\AnotherFile.msi C:\folder\efgh.txt C:\folder\FourthFile.msi C:\folder\ijkl.txt 

               But was:  "C:\folder\18a.txt"

基本上,整个描述显示在错误消息的Expected:部分中。 这是约束类

public class FileVerification : 
NUnit.Framework.Constraints.FileOrDirectoryExistsConstraint
{
    private string Path { get; }
    private string Message { get; }
    public FileVerification(string expected, string message)
    {
        Path = expected;
        Message = message;
    }

    public FileVerification(string expected, string message, params object[] args)
    {

    }

    public override ConstraintResult ApplyTo<TActual>(TActual actual)
    {
        if(!base.ApplyTo(actual).IsSuccess)
        {
            return new ConstraintResult(this, actual, false);
        }
        return new ConstraintResult(this, actual, true);
    }

    public override string Description
    {
        get
        {
            string fileName = Path.Split('\\').Last();
            string extension = fileName.Split('.').Last();
            string directoryPath = Path.Remove(Path.LastIndexOf('\\'));
            IEnumerable<string> files = Directory.EnumerateFiles(directoryPath);//.Where(f => f.EndsWith(extension)).Select(fn => fn.Split('\\').Last());
            return $"{Message}\n\tExpected: {fileName} to exist in {directoryPath}\n\tBut was: {string.Join(" ", files)}\n";
        }
    }

    public override string DisplayName
    {
        get
        {
            return "Just a DisplayName";
        }
    }

    public override string ToString()
    {
        return "Expected 'FILENAME' to exists in 'DIRECTORY'";
    }
}

0 个答案:

没有答案