Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ensure that null never matches It.IsRegex #385

Merged
merged 1 commit into from
Jun 21, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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