The place for .NET enthusiasts, Azure lovers, and backend developers

MSTest StringAssert class - an overview

2019-03-20 2 min read Blog
Just a second!
If you are here, it means that you are a software developer. So, you know that storage, networking, and domain management have a cost .

If you want to support this blog, please ensure that you have disabled the adblocker for this site. I configured Google AdSense to show as few ADS as possible - I don't want to bother you with lots of ads, but I still need to add some to pay for the resources for my site.

Thank you for your understanding.
- Davide

This is the second part of our journey through the Unit Test classes provided with VisualStudio. We already had a look at the Assert class, where had a glimpse of its methods. Now we’ll have a look at the StringAssert class, that, as you can imagine, provides some useful methods for string evaluation.

The StringAssert class

This class belongs to Microsoft.VisualStudio.TestTools.UnitTesting namespace. It’s a small class with few methods: maybe that’s the reason it is not preferred over the Assert class when testing a string.


This method checks if the actual string contains the expected string.

public void TestContains()
    string full = "Duck Avenger";
    string substring = "Aveng";
    StringAssert.Contains(full, substring); //OK
    substring = "AVEN";
    StringAssert.EndsWith(full, substring); //KO


Obviously it checks if the first parameters starts with a substring - that is the second parameter.

public void TestStartsWith()
    string full = "Donald Duck";
    string substring = "Don";
    StringAssert.StartsWith(full, substring); //OK
    substring = "don";
    StringAssert.StartsWith(full, substring); //KO

As you can see, the comparison is case sensitive, so the second check will fail.


Well, you can imagine… Also, the comparison is case sensitive.

public void TestEndsWith()
    string full = "Uncle Scrooge";
    string substring = "ooge";
    StringAssert.EndsWith(full, substring); //OK
    substring = "OOGE";
    StringAssert.EndsWith(full, substring); //KO


StringAssert.Matches and StringAssert.DoesNotMatch are a bit more complicated, since they involve regular expressions.

public void TestRegex()
    Regex regex = new Regex(@"[a-z]+");
    StringAssert.Matches("foo", regex);
    StringAssert.DoesNotMatch("123", regex);

This article first appeared on Code4IT

Wrapping Up

In my opinion, by now only the Matches method is useful. The others are missing important capabilities, like a parameter for specifying if the comparison is case sensitive and the possibility to specify the CultureInfo.

Another functionality that is missing is the possibility to test the negative counterpart of those methods (except for Matches and DoesNotMatch). I mean, I cannot test if a string does not start with a substring.

In the next article of this series, I’m going to talk about the CollectionAssert class. That is about… suspense…