Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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,7 +64,6 @@ 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);
Expand Down
48 changes: 48 additions & 0 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> SetupIMyIntMock").And
.Contains("public IMockVerify<MyCode.IMyInt> VerifyOnIMyIntMock"),
That(result.Sources["MockForIMyService_IMyInt_1Extensions.g.cs"])
.Contains("public IMockSetup<OtherNamespace.IMyInt> SetupIMyInt__2Mock").And
.Contains("public IMockVerify<OtherNamespace.IMyInt> VerifyOnIMyInt__2Mock"),
That(result.Diagnostics).IsEmpty()
);
}

[Fact]
public async Task WhenUsingCustomMockGeneratorAttribute_ShouldNotBeIncluded()
{
Expand Down
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.SetupIMyServiceMock.Method
.DoSomething(It.IsAny<int>())
.Do(() => invocationCount1++);
sut2.SetupIMyService__2Mock.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.VerifyOnIMyServiceMock.Invoked
.DoSomething(It.IsAny<int>())).Exactly(2);
await That(() => sut1.VerifyOnIMyService__2Mock)
.Throws<InvalidCastException>();
await That(() => sut2.VerifyOnIMyServiceMock)
.Throws<InvalidCastException>();
await That(sut2.VerifyOnIMyService__2Mock.Invoked
.DoSomething(It.IsAny<int>())).Exactly(3);
}
}
}
Loading