One should try to avoid coupling code to static classes as they are difficult to test.
That said, with your current code as is, it can be refactored to allow certain separations of concerns and a more fluent API via extension methods.
public static class ApplicationUtils {
public static Func<IIdentity> userFactory = () => WindowsIdentity.GetCurrent();
public static IIdentity CurrentUser { get { return userFactory(); } }
public static bool IsManager(this IIdentity identity) {
return identity != null && string.Compare(identity.Name, "AdminUser", true) == 0;
}
public static bool IsAuthenticated(this IIdentity identity) {
return identity != null && identity.IsAuthenticated;
}
}
The following test is used as an example to demonstrate how the above is used.
Moq was used as mocking framework
[TestMethod]
public void IsManager_Should_Return_True_For_AdminUser() {
//Arrange
var name = "AdminUser";
var identity = Mock.Of<IIdentity>(_ => _.Name == name);
ApplicationUtils.userFactory = () => identity;
//Act
var actual = ApplicationUtils.CurrentUser.IsManager();
//Assert
Assert.IsTrue(actual);
}
That done I would now like to suggest you refactor your code to make it more SOLID.
Abstract the functionality of getting the current user out into a service provider.
public interface IIdentityProvider {
IIdentity CurrentUser { get; }
}
Pretty simple with an even simpler implementation.
public class DefaultIdentityProvider : IIdentityProvider {
public IIdentity CurrentUser {
get { return WindowsIdentity.GetCurrent(); }
}
}
If using DI you can now inject the provider into dependent classes that have need to access the current user.
This allows the code to more flexible and maintainable as mocks/stubs of the provider and user can be used for isolated unit tests. The extension methods remain the same as they have very simple concerns.
Here is a simple example of a test for the extension method from earlier.
[TestMethod]
public void IsManager_Should_Return_True_For_AdminUser() {
//Arrange
var name = "AdminUser";
var identity = Mock.Of<IIdentity>(_ => _.Name == name);
var provider = Mock.Of<IIdentityProvider>(_ => _.CurrentUser == identity);
//Act
var actual = provider.CurrentUser.IsManager();
//Assert
Assert.IsTrue(actual);
}
Purely for demonstrative purposes, the test for the IsManager extension method only really needs an IIdentity to be exercised.
Assert.IsTrue(Mock.Of<IIdentity>(_ => _.Name == "AdminUser").IsManager());
WindowsIdentity. You only call the staticGetCurrentmethod. One way to test this is using shims or some other mocking framework.