简体   繁体   中英

How to test a directory path that matches a specific pattern/regex?

I have the following test which aims to ensure that file path generated is of a specific format. Using Nunit's fluent interfaces, how can I go about this?

I am having trouble with the regex.

  [Test]
    public void AssetControlPath_ShouldHaveFormat_BaseDir_YYYY_MMM_YYYYMMMDD() 
    {
        //Arrange
        var baseDir = "C:\\BaseDir";
        var fpBuilder = new FilePathBuilder(new DateTime(2010,10,10), baseDir );

        //Act
        var destinationPath = fpBuilder.AssetControlPath();

        //Assert
        // destinationPath = C:\BasDir\2010\Oct\20101010
    Assert.That(destinationPath, Is.StringMatching(@"C:\\BaseDir\\d{4}\\[a-zA-Z]{3}\\d{8}"));              
    }

The unit test error XXX.FilepathBuilderTests.AssetControlPath_ShouldHaveFormat_BaseDir_YYYY_MMM_YYYYMMMDD: Expected: String matching "C:\\\\BaseDir\\\\d{4}\\\\[a-zA-Z]{3}\\\\d{8}" But was: "C:\\BaseDir\\2010\\Oct\\20101010"

Edit: I have actually switched the test to use @ChrisF's approach. The question however still stands.

A String.Split with \\ as the split character and then check that you get the right number of elements (5) and that each element is the expected value might be:

a) be clearer in what the intent of the test is and

b) easier to maintain.

@"C:\\BaseDir\\d{4}\\[a-zA-Z]{3}]\\d{8}"
//                              /\ extra bracket

Also you have a problem with \\ escaping, you need \\\\\\d{4} and \\\\\\d{8} , you want to match xxx\\20101010 and not xxx20101010 . The following fix matches correct:

var str = @"C:\BaseDir\2010\Oct\20101010";
var re = new Regex(@"C:\\BaseDir\\\d{4}\\[a-zA-Z]{3}\\\d{8}", RegexOptions.IgnoreCase);
var result = re.IsMatch(str); // true

You have an extra closing square bracket!! remove that and it chould be fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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