下面是我的测试代码,该代码将验证注入的关联ID是否由自定义提供程序返回。我还给了我要测试的具体课程
[Test]
public void ShouldReturnCorrelationId()
{
// Arrange
var correlationId = Guid.NewGuid().ToString();
var fixture = new Fixture();
fixture.Customize(new AutoMoqCustomization());
// Register dependency object
fixture.Register(
() => {
var message = new HttpRequestMessage();
message.Headers.Add(HttpRequestHeaderFields.CorrelationId, correlationId);
return message;
});
var target = fixture.Create<CorrelationIdProvider>();
// Act
var result = target.GetCustomCorrelationId(); // Custom extension method which reads from header
// Assert
result.Should().BeEquivalentTo(correlationId);
}
public class CorrelationIdProvider : ICorrelationIdProvider
{
private readonly HttpRequestMessage currentRequest;
public CorrelationIdProvider(HttpRequestMessage currentRequest)
{
// I do not get my custom header here. Why?
this.currentRequest = currentRequest;
}
public string GetCustomCorrelationId()
{
return this.currentRequest?.GetCustomCorrelationId();
}
}
public static string GetCustomCorrelationId(this HttpRequestMessage request)
{
IEnumerable<string> result;
request.Headers.TryGetValues(HttpRequestHeaderFields.CorrelationId, out result);
return result?.Single();
}
我没有在测试中设置的自定义标头。为什么? 测试失败并显示以下消息
预期结果等于 “ 4059afe7-4ffe-4256-a6c7-c0ea7f4e4942”,但发现为空。
我必须对具体的类使用Fixture.Create(),因为它不能让我简单地初始化构造函数并传递HttpMessage。它将引发错误“方法未找到异常”。可能是因为它是抽象的,无法找出它来创建默认构造函数。