C# 使用moq的扩展方法的单元测试
我有两种扩展方法,如下所示C# 使用moq的扩展方法的单元测试,c#,unit-testing,moq,extension-methods,C#,Unit Testing,Moq,Extension Methods,我有两种扩展方法,如下所示 public static string FindFirstValue(this ClaimsPrincipal principal, string claimType, bool throwIfNotFound = false) { string value = principal.FindFirst(claimType)?.Value; if (throwIfNotFound && string.IsNullOrWhiteSpace
public static string FindFirstValue(this ClaimsPrincipal principal, string claimType, bool throwIfNotFound = false)
{
string value = principal.FindFirst(claimType)?.Value;
if (throwIfNotFound && string.IsNullOrWhiteSpace(value))
{
throw new InvalidOperationException(
string.Format(CultureInfo.InvariantCulture, "The supplied principal does not contain a claim of type {0}", claimType));
}
return value;
}
public static string GetObjectIdentifierValue(this ClaimsPrincipal principal, bool throwIfNotFound = true)
{
return principal.FindFirstValue("http://schemas.microsoft.com/identity/claims/objectidentifier", throwIfNotFound);
}
我听说不可能对扩展方法进行单元测试,因为它们是静态的。
只是想看看是否有人有想法使用Moq对上述扩展方法进行单元测试
有人能给我指出正确的方向吗?您的扩展方法是围绕FindFirst的包装器,所以这就是您真正想要模拟的方法。您很幸运:,因为clainprincipal.FindFirst是虚拟方法,所以可以模拟它
//Arrange
var principal = new Mock<ClaimsPrincipal>();
principal
.Setup(m => m.FindFirst(It.IsAny<string>()))
.Returns(new Claim("name", "John Doe"));
//Act
string value = principal.Object.FindFirstValue("claimType", true);
//Assert
Assert.AreEqual("John Doe", value);
我听说不可能对扩展方法进行单元测试,因为它们
它们是静态的
这通常不是真的。如果一个静态方法不依赖于在其体内创建依赖项,并且对于一个特定的输入得到一个特定的输出,那么您肯定可以对它进行单元测试
在您的情况下,可以避免使用Moq对这些扩展方法进行单元测试。您可以创建ClaimsPrincipal的实例,并使用这些实例测试扩展方法。下面是一些示例:
[Test]
public void WhenClaimTypeIsMissingAndAvoidExceptions_FindFirstValue_Returns_Null()
{
var principal = new ClaimsPrincipal();
var value = principal.FindFirstValue("claim type value");
Assert.IsNull(value);
}
[Test]
public void WhenClaimTypeIsMissingAndThrowExceptions_FindFirstValue_ThrowsException()
{
var principal = new ClaimsPrincipal();
var claimType = "claim type value";
Assert.Throws(Is.TypeOf<InvalidOperationException>()
.And.Message.EqualTo($"The supplied principal does not contain a claim of type {claimType}")
, () => principal.FindFirstValue(claimType, throwIfNotFound: true));
}
[Test]
public void WhenClaimTypeIsFound_FindFirstValue_ReturnsTheValue()
{
var principal = new ClaimsPrincipal();
principal.AddIdentity(new ClaimsIdentity(new List<Claim> {new Claim("type", "1234")}));
var value = principal.FindFirstValue("type");
Assert.AreEqual(value,"1234");
}