GFramework/GFramework.SourceGenerators.Tests/rule/ContextAwareGeneratorTests.cs
GwWuYou 603b06325d refactor(source-generators): 优化ContextAware生成器实现并添加快照测试
- 为ContextAwareGenerator添加详细的XML文档注释
- 简化接口验证逻辑,合并条件判断语句
- 修正特性数据参数命名,统一使用attr命名
- 为接口实现方法添加global::前缀以确保类型解析正确
- 移除未使用的回退方法体,简化方法实现逻辑
- 新增GeneratorSnapshotTest通用快照测试类
- 添加ContextAwareGeneratorSnapshotTests快照测试
- 移除原有的硬编码期望值测试方法
- 修正接口实现中的全局命名空间前缀格式
2025-12-29 20:30:54 +08:00

90 lines
3.8 KiB
C#

using GFramework.SourceGenerators.rule;
using GFramework.SourceGenerators.Tests.core;
using NUnit.Framework;
namespace GFramework.SourceGenerators.Tests.rule;
[TestFixture]
public class ContextAwareGeneratorTests
{
[Test]
public async Task Generates_ContextAware_Code_When_Interface_Inherits_IContextAware()
{
const string source = """
using System;
namespace GFramework.SourceGenerators.Abstractions.rule
{
[AttributeUsage(AttributeTargets.Class)]
public sealed class ContextAwareAttribute : Attribute
{
}
}
namespace TestApp
{
using GFramework.SourceGenerators.Abstractions.rule;
using GFramework.Core.Abstractions.rule;
public interface IMyRuleContextAware : IContextAware
{
}
[ContextAware]
public partial class MyRule : IMyRuleContextAware
{
}
}
""";
const string frameworkStub = """
namespace GFramework.Core.Abstractions.rule
{
public interface IContextAware
{
void SetContext(
GFramework.Core.Abstractions.architecture.IArchitectureContext context);
GFramework.Core.Abstractions.architecture.IArchitectureContext GetContext();
}
}
namespace GFramework.Core.Abstractions.architecture
{
public interface IArchitectureContext {}
}
""";
const string expected = """
// <auto-generated/>
#nullable enable
namespace TestApp;
partial class MyRule
{
/// <summary>
/// 自动注入的架构上下文
/// </summary>
protected GFramework.Core.Abstractions.architecture.IArchitectureContext Context { get; private set; } = null!;
void global::GFramework.Core.Abstractions.rule.IContextAware.SetContext(global::GFramework.Core.Abstractions.architecture.IArchitectureContext context)
{
Context = context;
}
global::GFramework.Core.Abstractions.architecture.IArchitectureContext global::GFramework.Core.Abstractions.rule.IContextAware.GetContext()
{
return Context;
}
}
""";
await GeneratorTest<ContextAwareGenerator>.RunAsync(
source + "\n" + frameworkStub,
("MyRule.ContextAware.g.cs", expected)
);
}
}