Skip to content
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
18 changes: 16 additions & 2 deletions Source/Mockolate.SourceGenerators/MockGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ void IIncrementalGenerator.Initialize(IncrementalGeneratorInitializationContext
private static void Execute(ImmutableArray<MockClass> mocksToGenerate, SourceProductionContext context)
{
(string Name, MockClass MockClass)[] namedMocksToGenerate = CreateNames(mocksToGenerate);
Dictionary<(string? Namespace, string ClassName), HashSet<string>> allUsedNames = [];
HashSet<(string? BaseNamespace, string BaseClassName, string? Namespace, string ClassName)>
generatedAdditionalInterfacesByBaseType = new();

Expand All @@ -55,17 +56,30 @@ private static void Execute(ImmutableArray<MockClass> mocksToGenerate, SourcePro
if (mockToGenerate.MockClass.AdditionalImplementations.Any() && mockToGenerate.MockClass.Delegate is null)
{
Class[] interfacesToGenerate = mockToGenerate.MockClass.DistinctAdditionalImplementations()
.Where(impl => generatedAdditionalInterfacesByBaseType .Add(
.Where(impl => generatedAdditionalInterfacesByBaseType.Add(
(mockToGenerate.MockClass.Namespace, mockToGenerate.MockClass.ClassName,
impl.Namespace, impl.ClassName)))
.ToArray();

if (interfacesToGenerate.Length > 0)
{
(string? Namespace, string ClassName) key = (mockToGenerate.MockClass.Namespace,
mockToGenerate.MockClass.ClassName);
HashSet<string> usedNames;
if (allUsedNames.ContainsKey(key))
{
usedNames = allUsedNames[key];
}
else
{
Comment thread
vbreuss marked this conversation as resolved.
usedNames = new HashSet<string>();
allUsedNames.Add(key, usedNames);
}

context.AddSource($"MockFor{mockToGenerate.Name}Extensions.g.cs",
SourceText.From(
Sources.Sources.ForMockCombinationExtensions(mockToGenerate.Name, mockToGenerate.MockClass,
interfacesToGenerate),
interfacesToGenerate, usedNames),
Encoding.UTF8));
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,11 @@ internal static partial class Sources
{
private static readonly Regex InvalidIdentifierChars = new("[^a-zA-Z0-9_]", RegexOptions.Compiled);

public static string ForMockCombinationExtensions(string name, MockClass mockClass,
IEnumerable<Class> distinctAdditionalImplementations)
public static string ForMockCombinationExtensions(
string name,
MockClass mockClass,
IEnumerable<Class> distinctAdditionalImplementations,
HashSet<string> usedNames)
Comment thread
vbreuss marked this conversation as resolved.
{
StringBuilder sb = InitializeBuilder([
"Mockolate.Exceptions",
Expand Down Expand Up @@ -61,10 +64,9 @@ private static Mock<T> GetMockOrThrow<T>(T subject)
sb.Append("\textension(").Append(mockClass.ClassFullName).AppendLine(" subject)");
sb.AppendLine("\t{");

HashSet<string> usedNames = [];
foreach (Class @class in distinctAdditionalImplementations)
{
AppendAdditionalMockExtensions(sb, @class, usedNames);
AppendAdditionalMockExtensions(sb, mockClass, @class, usedNames);
}

sb.AppendLine("\t}");
Expand All @@ -74,15 +76,19 @@ private static Mock<T> GetMockOrThrow<T>(T subject)
return sb.ToString();
}

private static void AppendAdditionalMockExtensions(StringBuilder sb, Class @class, HashSet<string> usedNames)
private static void AppendAdditionalMockExtensions(StringBuilder sb, MockClass mockClass, Class @class,
HashSet<string> usedNames)
{
sb.AppendLine();
int nameSuffix = 1;
string sanitizedClassName = InvalidIdentifierChars.Replace(@class.ClassName, "_");
string sanitizedClassName = InvalidIdentifierChars.Replace(
mockClass.Namespace == @class.Namespace
? @class.ClassName
: $"{@class.Namespace}.{@class.ClassName}", "_");
string name = sanitizedClassName;
while (!usedNames.Add(name))
{
name = $"{sanitizedClassName}__{++nameSuffix}";
name = $"{sanitizedClassName}_{++nameSuffix}";
}

string mockExpression =
Expand All @@ -93,8 +99,8 @@ private static void AppendAdditionalMockExtensions(StringBuilder sb, Class @clas
.Append("\" />")
.AppendLine();
sb.Append("\t\t/// </summary>").AppendLine();
sb.Append("\t\tpublic IMockSetup<").Append(@class.ClassFullName).Append("> Setup").Append(name)
.Append("Mock")
sb.Append("\t\tpublic IMockSetup<").Append(@class.ClassFullName).Append("> Setup_").Append(name)
.Append("_Mock")
.AppendLine();
sb.Append("\t\t\t=> ").Append(mockExpression).AppendLine();

Expand All @@ -106,8 +112,8 @@ private static void AppendAdditionalMockExtensions(StringBuilder sb, Class @clas
.Append(@class.ClassFullName.EscapeForXmlDoc())
.Append("\" />").AppendLine();
sb.Append("\t\t/// </summary>").AppendLine();
sb.Append("\t\tpublic IMockRaises<").Append(@class.ClassFullName).Append("> RaiseOn")
.Append(name).Append("Mock").AppendLine();
sb.Append("\t\tpublic IMockRaises<").Append(@class.ClassFullName).Append("> RaiseOn_")
.Append(name).Append("_Mock").AppendLine();
sb.Append("\t\t\t=> ").Append(mockExpression).AppendLine();
}

Expand All @@ -116,8 +122,8 @@ private static void AppendAdditionalMockExtensions(StringBuilder sb, Class @clas
sb.Append("\t\t/// Verifies the interactions with the mocked subject of <see cref=\"")
.Append(@class.ClassFullName.EscapeForXmlDoc()).Append("\" /> on the mock.").AppendLine();
sb.Append("\t\t/// </summary>").AppendLine();
sb.Append("\t\tpublic IMockVerify<").Append(@class.ClassFullName).Append("> VerifyOn").Append(name)
.Append("Mock")
sb.Append("\t\tpublic IMockVerify<").Append(@class.ClassFullName).Append("> VerifyOn_").Append(name)
.Append("_Mock")
.AppendLine();
sb.Append("\t\t\t=> ").Append(mockExpression).AppendLine();
}
Expand Down
12 changes: 6 additions & 6 deletions Tests/Mockolate.ExampleTests/ExampleTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,14 @@ public async Task Any_ShouldAlwaysMatch()
Guid id = Guid.NewGuid();
MyClass mock =
Mock.Create<MyClass, IExampleRepository, IOrderRepository>(BaseClass.WithConstructorParameters(3));
mock.SetupIExampleRepositoryMock.Method.AddUser(
mock.Setup_IExampleRepository_Mock.Method.AddUser(
It.IsAny<string>())
.Returns(new User(id, "Alice"));

User result = ((IExampleRepository)mock).AddUser("Bob");

await That(result).IsEqualTo(new User(id, "Alice"));
mock.VerifyOnIExampleRepositoryMock.Invoked.AddUser(It.Is("Bob")).Once();
mock.VerifyOn_IExampleRepository_Mock.Invoked.AddUser(It.Is("Bob")).Once();
}

[Fact]
Expand Down Expand Up @@ -93,14 +93,14 @@ public async Task WithAdditionalInterface_ShouldWork()
{
Guid id = Guid.NewGuid();
IExampleRepository mock = Mock.Create<IExampleRepository, IOrderRepository>();
mock.SetupIOrderRepositoryMock.Method
mock.Setup_IOrderRepository_Mock.Method
.AddOrder(It.IsAny<string>())
.Returns(new Order(id, "Order1"));

Order result = ((IOrderRepository)mock).AddOrder("foo");

await That(result.Name).IsEqualTo("Order1");
mock.VerifyOnIOrderRepositoryMock.Invoked.AddOrder(It.Is("foo")).Once();
mock.VerifyOn_IOrderRepository_Mock.Invoked.AddOrder(It.Is("foo")).Once();
await That(mock).Is<IExampleRepository>();
await That(mock).Is<IOrderRepository>();
}
Expand Down Expand Up @@ -142,7 +142,7 @@ public async Task WithExplicitCastToAdditionalInterfaceSetup_ShouldWork()
Order result = ((IOrderRepository)mock).AddOrder("foo");

await That(result.Name).IsEqualTo("Order1");
mock.VerifyOnIOrderRepositoryMock.Invoked.AddOrder(It.Is("foo")).Once();
mock.VerifyOn_IOrderRepository_Mock.Invoked.AddOrder(It.Is("foo")).Once();
await That(mock).Is<IExampleRepository>();
await That(mock).Is<IOrderRepository>();
}
Expand All @@ -152,7 +152,7 @@ public async Task WithExplicitCastToAdditionalInterfaceVerify_ShouldWork()
{
Guid id = Guid.NewGuid();
IExampleRepository mock = Mock.Create<IExampleRepository, IOrderRepository>();
mock.SetupIOrderRepositoryMock.Method
mock.Setup_IOrderRepository_Mock.Method
.AddOrder(It.IsAny<string>())
.Returns(new Order(id, "Order1"));

Expand Down
12 changes: 6 additions & 6 deletions Tests/Mockolate.Internal.Tests/WebTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,14 @@ public async Task WhenParameterDoesNotImplementIHttpRequestMessagePropertyParame
{
ItExtensions.IHttpContentParameter parameter =
Mock.Create<ItExtensions.IHttpContentParameter, IParameter>();
parameter.SetupIParameterMock.Method.Matches(It.IsAny<object?>()).Returns(true);
parameter.Setup_Mockolate_Parameters_IParameter_Mock.Method.Matches(It.IsAny<object?>()).Returns(true);

ItExtensions.IStringContentBodyParameter sut = parameter.WithString("foo");

bool result = ((IHttpRequestMessagePropertyParameter<HttpContent?>)sut).Matches(null, null);

await That(result).IsTrue();
await That(parameter.VerifyOnIParameterMock.Invoked
await That(parameter.VerifyOn_Mockolate_Parameters_IParameter_Mock.Invoked
.Matches(It.IsNull<object?>()))
.Once();
}
Expand All @@ -54,19 +54,19 @@ public async Task WhenParameterImplementsIHttpRequestMessagePropertyParameter_Sh
ItExtensions.IHttpContentParameter parameter =
Mock.Create<ItExtensions.IHttpContentParameter, IParameter,
IHttpRequestMessagePropertyParameter<HttpContent?>>();
parameter.SetupIParameterMock.Method.Matches(It.IsAny<object?>()).Returns(false);
parameter.SetupIHttpRequestMessagePropertyParameter_HttpContent_Mock.Method
parameter.Setup_Mockolate_Parameters_IParameter_Mock.Method.Matches(It.IsAny<object?>()).Returns(false);
parameter.Setup_IHttpRequestMessagePropertyParameter_HttpContent__Mock.Method
.Matches(It.IsAny<HttpContent?>(), It.IsAny<HttpRequestMessage?>()).Returns(true);

ItExtensions.IStringContentBodyParameter sut = parameter.WithString("foo");

bool result = ((IHttpRequestMessagePropertyParameter<HttpContent?>)sut).Matches(null, null);

await That(result).IsTrue();
await That(parameter.VerifyOnIHttpRequestMessagePropertyParameter_HttpContent_Mock.Invoked
await That(parameter.VerifyOn_IHttpRequestMessagePropertyParameter_HttpContent__Mock.Invoked
.Matches(It.IsNull<HttpContent?>(), It.IsNull<HttpRequestMessage?>()))
.Once();
await That(parameter.VerifyOnIParameterMock.Invoked
await That(parameter.VerifyOn_Mockolate_Parameters_IParameter_Mock.Invoked
.Matches(It.IsNull<object?>()))
.Never();
}
Expand Down
2 changes: 1 addition & 1 deletion Tests/Mockolate.SourceGenerators.Tests/GeneralTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -354,7 +354,7 @@ public interface IMyInterface

await That(result.Sources).ContainsKey("MockForIMyInterface_IMyInterface_IMyInterfaceExtensions.g.cs")
.WhoseValue
.Contains("public IMockSetup<MyCode.N2.IMyInterface> SetupIMyInterface__2Mock");
.Contains("public IMockSetup<MyCode.N2.IMyInterface> Setup_MyCode_N2_IMyInterface_Mock");
}

[Fact]
Expand Down
68 changes: 58 additions & 10 deletions Tests/Mockolate.SourceGenerators.Tests/MockGeneratorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,54 @@ await ThatAll(
);
}

[Fact]
public async Task WhenNamesConflictForAdditionalClassesInDifferentNamespaces_ShouldAppendAnIndex()
Comment thread
vbreuss marked this conversation as resolved.
{
GeneratorResult result = Generator
.Run("""
using System;
using System.Threading;
using System.Threading.Tasks;
using Mockolate;

namespace MyCode
{
public class Program
{
public static void Main(string[] args)
{
_ = Mock.Create<IMyService, MyCode.IMyInt>();
_ = Mock.Create<IMyService, OtherNamespace.IMyInt>();
}
}

public interface IMyInt { }

public interface IMyService { }
}
namespace OtherNamespace
{
public interface IMyInt { }
}
""", typeof(HttpResponseMessage));

await ThatAll(
That(result.Sources.Keys).Contains([
"MockForIMyService_IMyInt.g.cs",
"MockForIMyService_IMyInt_1.g.cs",
"MockForIMyService_IMyIntExtensions.g.cs",
"MockForIMyService_IMyInt_1Extensions.g.cs",
]).InAnyOrder(),
That(result.Sources["MockForIMyService_IMyIntExtensions.g.cs"])
.Contains("public IMockSetup<MyCode.IMyInt> Setup_IMyInt_Mock").And
.Contains("public IMockVerify<MyCode.IMyInt> VerifyOn_IMyInt_Mock"),
That(result.Sources["MockForIMyService_IMyInt_1Extensions.g.cs"])
.Contains("public IMockSetup<OtherNamespace.IMyInt> Setup_OtherNamespace_IMyInt_Mock").And
.Contains("public IMockVerify<OtherNamespace.IMyInt> VerifyOn_OtherNamespace_IMyInt_Mock"),
That(result.Diagnostics).IsEmpty()
);
}

[Fact]
public async Task WhenUsingCustomMockGeneratorAttribute_ShouldNotBeIncluded()
{
Expand Down Expand Up @@ -459,19 +507,19 @@ await That(result.Sources)
.DoesNotContainKey("MockForIBaseInterface_IAdditionalInterface1_IAdditionalInterface2_ICommonInterfaceExtensions.g.cs");

await That(result.Sources["MockForIBaseInterface_ICommonInterfaceExtensions.g.cs"])
.Contains("SetupICommonInterfaceMock").And
.Contains("VerifyOnICommonInterfaceMock");
.Contains("Setup_ICommonInterface_Mock").And
.Contains("VerifyOn_ICommonInterface_Mock");

await That(result.Sources["MockForIBaseInterface_ICommonInterface_IAdditionalInterface1Extensions.g.cs"])
.DoesNotContain("SetupICommonInterfaceMock").And
.DoesNotContain("VerifyOnICommonInterfaceMock").And
.Contains("SetupIAdditionalInterface1Mock").And
.Contains("VerifyOnIAdditionalInterface1Mock");
.DoesNotContain("Setup_ICommonInterface_Mock").And
.DoesNotContain("VerifyOn_ICommonInterface_Mock").And
.Contains("Setup_IAdditionalInterface1_Mock").And
.Contains("VerifyOn_IAdditionalInterface1_Mock");

await That(result.Sources["MockForIBaseInterface_IAdditionalInterface2_ICommonInterfaceExtensions.g.cs"])
.DoesNotContain("SetupICommonInterfaceMock").And
.DoesNotContain("VerifyOnICommonInterfaceMock").And
.Contains("SetupIAdditionalInterface2Mock").And
.Contains("VerifyOnIAdditionalInterface2Mock");
.DoesNotContain("Setup_ICommonInterface_Mock").And
.DoesNotContain("VerifyOn_ICommonInterface_Mock").And
.Contains("Setup_IAdditionalInterface2_Mock").And
.Contains("VerifyOn_IAdditionalInterface2_Mock");
}
}
33 changes: 33 additions & 0 deletions Tests/Mockolate.Tests/MockTests.CreateTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -657,5 +657,38 @@ await That(Act).Throws<MockException>()
.WithMessage(
"The mock declaration has 1 additional implementation that is not an interface: Mockolate.Tests.TestHelpers.MyServiceBase");
}

[Fact]
public async Task WithAdditionalInterfacesFromDifferentNamespaces_ShouldHaveUniqueName()
{
int invocationCount1 = 0;
int invocationCount2 = 0;
IChocolateDispenser sut1 = Mock.Create<IChocolateDispenser, TestHelpers.IMyService>();
IChocolateDispenser sut2 = Mock.Create<IChocolateDispenser, TestHelpers.Other.IMyService>();

sut1.Setup_IMyService_Mock.Method
.DoSomething(It.IsAny<int>())
.Do(() => invocationCount1++);
sut2.Setup_Mockolate_Tests_TestHelpers_Other_IMyService_Mock.Method
.DoSomething(It.IsAny<int>())
.Do(() => invocationCount2++);

((TestHelpers.IMyService)sut1).DoSomething(1);
((TestHelpers.IMyService)sut1).DoSomething(2);
((TestHelpers.Other.IMyService)sut2).DoSomething(1);
((TestHelpers.Other.IMyService)sut2).DoSomething(2);
((TestHelpers.Other.IMyService)sut2).DoSomething(3);

await That(invocationCount1).IsEqualTo(2);
await That(invocationCount2).IsEqualTo(3);
await That(sut1.VerifyOn_IMyService_Mock.Invoked
.DoSomething(It.IsAny<int>())).Exactly(2);
await That(() => sut1.VerifyOn_Mockolate_Tests_TestHelpers_Other_IMyService_Mock)
.Throws<InvalidCastException>();
await That(() => sut2.VerifyOn_IMyService_Mock)
.Throws<InvalidCastException>();
await That(sut2.VerifyOn_Mockolate_Tests_TestHelpers_Other_IMyService_Mock.Invoked
.DoSomething(It.IsAny<int>())).Exactly(3);
}
}
}
4 changes: 2 additions & 2 deletions Tests/Mockolate.Tests/MockTests.FactoryTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -191,8 +191,8 @@ public async Task Create_WithSameNamedInterfaces_ShouldAppendIndex()
MyServiceBase mock =
factory.Create<MyServiceBase, IMyService, TestHelpers.IMyService, TestHelpers.Other.IMyService>();

mock.SetupIMyServiceMock.Method.DoSomething(It.IsAny<int>()).Do(() => isDoSomethingCalled1 = true);
mock.SetupIMyService__2Mock.Method.DoSomething(It.IsAny<int>()).Do(() => isDoSomethingCalled2 = true);
mock.Setup_IMyService_Mock.Method.DoSomething(It.IsAny<int>()).Do(() => isDoSomethingCalled1 = true);
mock.Setup_Mockolate_Tests_TestHelpers_Other_IMyService_Mock.Method.DoSomething(It.IsAny<int>()).Do(() => isDoSomethingCalled2 = true);

((TestHelpers.IMyService)mock).DoSomething(1);

Expand Down
Loading