Skip to content

Commit

Permalink
Ensure that null never matches It.IsRegex
Browse files Browse the repository at this point in the history
Currently, matching `null` against any `It.IsRegex` placeholder will
result in an `ArgumentNullException` being thrown by the framework.
This is unintuitive.

This changes Moq behavior so that `null` will simply never match any
`It.IsRegex`.
  • Loading branch information
stakx committed Jun 21, 2017
1 parent f001f6d commit 62f5413
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
8 changes: 6 additions & 2 deletions Source/It.cs
Original file line number Diff line number Diff line change
Expand Up @@ -138,21 +138,25 @@ public static TValue IsNotIn<TValue>(params TValue[] items)
/// <include file='It.xdoc' path='docs/doc[@for="It.IsRegex(regex)"]/*'/>
public static string IsRegex(string regex)
{
Guard.NotNull(() => regex, regex);

// The regex is constructed only once.
var re = new Regex(regex);

// But evaluated every time :)
return Match<string>.Create(value => re.IsMatch(value), () => It.IsRegex(regex));
return Match<string>.Create(value => value != null && re.IsMatch(value), () => It.IsRegex(regex));
}

/// <include file='It.xdoc' path='docs/doc[@for="It.IsRegex(regex,options)"]/*'/>
public static string IsRegex(string regex, RegexOptions options)
{
Guard.NotNull(() => regex, regex);

// The regex is constructed only once.
var re = new Regex(regex, options);

// But evaluated every time :)
return Match<string>.Create(value => re.IsMatch(value), () => It.IsRegex(regex, options));
return Match<string>.Create(value => value != null && re.IsMatch(value), () => It.IsRegex(regex, options));
}
}
}
28 changes: 28 additions & 0 deletions UnitTests/MatchersFixture.cs
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,34 @@ public void RegexMatchesAndEagerlyEvaluates()
Assert.Equal("foo", mock.Object.Execute("B"));
}

[Fact]
public void RegexMustNotBeNull()
{
Assert.Throws<ArgumentNullException>(() => It.IsRegex(null));
}

[Fact]
public void RegexMustNotBeNullWithOptions()
{
Assert.Throws<ArgumentNullException>(() => It.IsRegex(null, RegexOptions.None));
}

[Fact]
public void NullNeverMatchesRegex()
{
var mock = new Mock<IFoo>();
mock.Setup(foo => foo.Execute(It.IsRegex(".*"))).Returns("foo");
Assert.NotEqual("foo", mock.Object.Execute(null));
}

[Fact]
public void NullNeverMatchesRegexWithOptions()
{
var mock = new Mock<IFoo>();
mock.Setup(foo => foo.Execute(It.IsRegex(".*", RegexOptions.None))).Returns("foo");
Assert.NotEqual("foo", mock.Object.Execute(null));
}

[Fact]
public void MatchesEvenNumbersWithLambdaMatching()
{
Expand Down

0 comments on commit 62f5413

Please sign in to comment.