Reputation: 497
I have two extension method like the below,
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);
}
I have heard it is impossible to unit test extension methods as they are static. Just wanted to check if anybody has an idea to unit test the above extension methods using Moq?
Could anyone please point me to right direction?
Upvotes: 2
Views: 8549
Reputation: 53958
I have heard it is impossible to unit test extension methods as they are static.
This is not generally true. If a static method does not rely on creating the dependencies it has inside her body and for a specific input gets a specific output, you can definitely unit test it.
In your case, you can avoid using Moq for unit testing these extensions methods. You could create instances of ClaimsPrincipal
and test your extension methods using those instances. Below you will found some examples:
[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");
}
Upvotes: 2
Reputation: 9509
Your extension method is a wrapper around FindFirst
so that is the method you actually want to mock. You are lucky :), since ClaimPrincipal.FindFirst
is virtual
method it is possible to mock it.
//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);
Upvotes: 2