From 24555cebb2ff82af7a64a4cd64d6e3f61f006dc4 Mon Sep 17 00:00:00 2001 From: stakx Date: Wed, 21 Jun 2017 10:30:29 +0200 Subject: [PATCH] Ensure that `null` never matches `It.IsRegex` 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`. --- Source/It.cs | 8 ++++++-- UnitTests/MatchersFixture.cs | 28 ++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/Source/It.cs b/Source/It.cs index 6392a0c4a..3777dc030 100644 --- a/Source/It.cs +++ b/Source/It.cs @@ -138,21 +138,25 @@ public static TValue IsNotIn(params TValue[] items) /// 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.Create(value => re.IsMatch(value), () => It.IsRegex(regex)); + return Match.Create(value => value != null && re.IsMatch(value), () => It.IsRegex(regex)); } /// 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.Create(value => re.IsMatch(value), () => It.IsRegex(regex, options)); + return Match.Create(value => value != null && re.IsMatch(value), () => It.IsRegex(regex, options)); } } } diff --git a/UnitTests/MatchersFixture.cs b/UnitTests/MatchersFixture.cs index 79dd7537b..355416fe8 100644 --- a/UnitTests/MatchersFixture.cs +++ b/UnitTests/MatchersFixture.cs @@ -183,6 +183,34 @@ public void RegexMatchesAndEagerlyEvaluates() Assert.Equal("foo", mock.Object.Execute("B")); } + [Fact] + public void RegexMustNotBeNull() + { + Assert.Throws(() => It.IsRegex(null)); + } + + [Fact] + public void RegexMustNotBeNullWithOptions() + { + Assert.Throws(() => It.IsRegex(null, RegexOptions.None)); + } + + [Fact] + public void NullNeverMatchesRegex() + { + var mock = new Mock(); + mock.Setup(foo => foo.Execute(It.IsRegex(".*"))).Returns("foo"); + Assert.NotEqual("foo", mock.Object.Execute(null)); + } + + [Fact] + public void NullNeverMatchesRegexWithOptions() + { + var mock = new Mock(); + mock.Setup(foo => foo.Execute(It.IsRegex(".*", RegexOptions.None))).Returns("foo"); + Assert.NotEqual("foo", mock.Object.Execute(null)); + } + [Fact] public void MatchesEvenNumbersWithLambdaMatching() {