ASP.NET Core unit test authorization - unit-testing

I try to create unit testing my authorization logic, but have problem for testing
await this.HttpContext.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme)));
I have error
No authentication handler is configured to handle the scheme: Cookies
Because he need CookieAuthenticationOptions
But how configuration for unit test I don't know
private static Mock<SignInManager<User>> GetSignInManagerMock(Mock<UserManager<User>> userManagerMock)
{
var context = new Mock<HttpContext>();
var contextAccessor = new Mock<IHttpContextAccessor>();
contextAccessor.Setup(x => x.HttpContext).Returns(context.Object);
return new Mock<SignInManager<User>>(userManagerMock.Object,
contextAccessor.Object,
new Mock<IUserClaimsPrincipalFactory<User>>().Object,
new Mock<IOptions<IdentityOptions>>().Object,
new Mock<ILogger<SignInManager<User>>>().Object);
}
private static Mock<UserManager<User>> GetUserManagerMock()
{
return new Mock<UserManager<User>>(new Mock<IUserStore<User>>().Object,
new Mock<IOptions<IdentityOptions>>().Object,
new Mock<IPasswordHasher<User>>().Object,
new IUserValidator<User>[0],
new IPasswordValidator<User>[0],
new Mock<ILookupNormalizer>().Object,
new Mock<IdentityErrorDescriber>().Object,
new Mock<IServiceProvider>().Object,
new Mock<ILogger<UserManager<User>>>().Object);
}
[Fact]
public async void Login_Corect_input_login_password_should_return_ok()
{
var stamp = Guid.NewGuid().ToString();
var user = new User
{
UserName = _fakeUserModel.UserName,
Email = _fakeUserModel.Email,
FirtName = _fakeUserModel.FirstName,
LastName = _fakeUserModel.LastName,
UserPicture = _fakeUserModel.UserPicture,
ConcurrencyStamp = stamp
};
var userManagerMock = GetUserManagerMock();
userManagerMock.Setup(s => s.FindByNameAsync(FakeData.UserName)).ReturnsAsync(user);
userManagerMock.Setup(s => s.GetRolesAsync(user)).ReturnsAsync(FakeData.Roles);
var signInManagerMock = GetSignInManagerMock(userManagerMock);
signInManagerMock.Setup(
s =>
s.PasswordSignInAsync(_fakeCorrectloginModel.UserName, _fakeCorrectloginModel.Password, false,
false))
.ReturnsAsync(Microsoft.AspNetCore.Identity.SignInResult.Success);
var controller = ControllerFactory.CreateFakeController<UserController>(false, userManagerMock.Object,
signInManagerMock.Object);
var response = await controller.Login(_fakeCorrectloginModel);
var result = Assert.IsType<JsonResult>(response);
var getModel = Assert.IsType<UserViewModel>(result.Value);
Assert.Equal(_fakeUserModel, getModel);
}
public static class ControllerFactory
{
public static T CreateFakeController<T>(bool isLoggedIn, params object[] arg) where T : Controller
{
var fakePrincipal = GetPrincipalMock(isLoggedIn).Object;
var fakeActionContext = new ActionContext
{
HttpContext = new DefaultHttpContext
{
User = fakePrincipal
},
ActionDescriptor = new ControllerActionDescriptor(),
RouteData = new RouteData()
};
var controller = (T)Activator.CreateInstance(typeof(T), arg);
controller.ControllerContext = new ControllerContext(fakeActionContext);
return controller;
}
public static Mock<ClaimsPrincipal> GetPrincipalMock(bool isLoggedIn)
{
var principalMock = new Mock<ClaimsPrincipal>();
principalMock.Setup(sg => sg.Identity).Returns(GetIdentityMock(isLoggedIn).Object);
principalMock.Setup(s => s.IsInRole(It.IsAny<string>())).Returns(false);
principalMock.Setup(s => s.Claims).Returns(new List<Claim>
{
GetClaim(HelpClaimTypes.Language, "ua")
});
return principalMock;
}
public static Mock<ClaimsIdentity> GetIdentityMock(bool isLoggedIn)
{
var identityMock = new Mock<ClaimsIdentity>();
identityMock.Setup(sg => sg.AuthenticationType).Returns(isLoggedIn ? FakeData.AuthenticationType : null);
identityMock.Setup(sg => sg.IsAuthenticated).Returns(isLoggedIn);
identityMock.Setup(sg => sg.Name).Returns(isLoggedIn ? FakeData.UserName : null);
return identityMock;
}
public static ClaimsIdentity GetClaimsIdentity(params Claim[] claims)
{
var identityMock = new ClaimsIdentity(claims);
return identityMock;
}
public static Claim GetClaim(string type, string value)
{
return new Claim(type, value);
}
}

Related

xUnit ClaimsPrincipal mock and passing into controller User is null

I have been reading articles trying to figure this one out. Structured off of this article How to add claims in a mock ClaimsPrincipal. I am still getting a null user from my controller and test fails on a null object of User inside the controller.
BusinessController
[Route("api/[controller]")]
[ApiController]
public class BusinessController : ControllerBase
{
private readonly IGBusinessRepository businessRepository;
private readonly IPersonRepository personRepository;
private readonly IUserClaims userClaims;
public BusinessController(IGBusinessRepository businessRepository,
IPersonRepository personRepository,
IUserClaims userClaims)
{
this.businessRepository = businessRepository;
this.personRepository = personRepository;
this.userClaims = userClaims;
}
// GET api/<BusinessController>/5
[HttpGet("{id}")]
[Authorize]
public async Task<IActionResult> GetBusiness(Guid businessId)
{
var userGuid = userClaims.GetUserGuid(User.Claims);
var ownerId = await personRepository.GetPersonIdByGUID(userGuid);
var business = await businessRepository.GetBusinessById(businessId);
if(business != null && business.OwnerId == businessId)
{
return Ok(business);
}
return BadRequest("Bad business id or your not the owner");
}
UserClaims
public class UserClaims : IUserClaims
{
public string GetUserGuid(IEnumerable<Claim> claims)
{
var claimType = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier";
var guidClaim = claims.Where(c => c.Type == claimType).Select(s => s.Value).SingleOrDefault();
return guidClaim;
}
}
TestIdentity
public class TestIdentity : ClaimsIdentity
{
public TestIdentity(params Claim[] claims) : base(claims)
{
}
}
TestPrincipal
public class TestPrincipal : ClaimsPrincipal
{
public TestPrincipal(params Claim[] claims) : base(new TestIdentity(claims))
{
}
}
BusinessControllerTests
public class BusinessControllerTests
{
//Controller
private readonly Mock<IGBusinessRepository> mockBusinessRepository;
private readonly Mock<IPersonRepository> mockPersonRepository;
private readonly Mock<IUserClaims> mockUserClaims;
private BusinessController controller;
//Objects
private Guid id = Guid.NewGuid();
public BusinessControllerTests()
{
mockBusinessRepository = new Mock<IGBusinessRepository>();
mockPersonRepository = new Mock<IPersonRepository>();
mockUserClaims = new Mock<IUserClaims>();
controller = new BusinessController(mockBusinessRepository.Object, mockPersonRepository.Object, mockUserClaims.Object);
}
[Fact]
public async Task GetBussiness_NotBusinessOwner_ReturnsBadRequest()
{
//Arrange
var userGuidString = Guid.NewGuid().ToString();
var ownerId = Guid.NewGuid();
var userClaim = new TestPrincipal(new Claim("name", "user#domain.com"));
Thread.CurrentPrincipal = userClaim;
//mockUserClaims.Setup(repo => repo.GetUserGuid(userClaim)).Returns(userGuidString);
mockPersonRepository.Setup(repo => repo.GetPersonIdByGUID(userGuidString));
mockBusinessRepository.Setup(repo => repo.GetBusinessById(id)).ReturnsAsync(business);
//Act
var result = await controller.GetBusiness(id);
//Assert
Assert.IsType<BadRequestResult>(result);
}
private GobiezBusiness business = new GobiezBusiness()
{
Id = new MongoDB.Bson.ObjectId(),
BusinessId = Guid.NewGuid(),
Name = "Test",
Email = "Test#helpme.com",
Address = "123 A street",
State = "WA",
ZipCode = "12345",
PhoneNumber = "123-456-7890",
OwnerId = Guid.NewGuid()
};
}
The controller was not arranged correctly to be able to access the principal
// ... omitted for brevity
var userClaim = new TestPrincipal(new Claim("name", "user#domain.com"));
var httpContext = new DefaultHttpContext() {
User = userClaim;
};
//Controller needs a controller context to access HttpContext
var controllerContext = new ControllerContext() {
HttpContext = httpContext
};
//assign context to controller
BusinessController controller = new BusinessController(
mockBusinessRepository.Object,
mockPersonRepository.Object,
mockUserClaims.Object)
{
ControllerContext = controllerContext
};
//Act
var result = await controller.GetBusiness(id);
// ... omitted for brevity
The controller should also be created within the scope of the test being executed.
This line in the subject under test
//...
var userGuid = userClaims.GetUserGuid(User.Claims);
//...
Should now return the created TestPrincipal arranged in the test

System.TypeLoadException: Could not load type 'Microsoft.EntityFrameworkCore.Query.Internal.IAsyncQueryProvider'

I am using testing my Identity actions in my .NET Core web application but keep running into problems. I recently found a way to create a mocked usermanager without running into problems with its parameters, but then a new error came to me that I can't find any solutions too: "System.TypeLoadException: Could not load type 'Microsoft.EntityFrameworkCore.Query.Internal.IAsyncQueryProvider'"
Here is my relevant code:
Setting up the mock usermanager:
var _userManager = new Mock<FakeUserManager>();
UserIdentity user1 = new UserIdentity() { Id = UserId1, UserName = "test#gmail.com", Score = 5 };
UserIdentity user2 = new UserIdentity() { Id = UserId2, UserName = "pragim#gmail.com", Score = 1 };
UserIdentity user3 = new UserIdentity() { Id = UserId3, UserName = "ajax#gmail.com", Score = 0 };
UserIdentity user4 = new UserIdentity() { Id = UserId4, UserName = "pim#gmail.com", Score = 4 };
List<UserIdentity> users = new List<UserIdentity>() { user1, user2, user3, user4 };
var mock = users.AsQueryable().BuildMock();
_userManager.Setup(x => x.Users).Returns(mock.Object);
var identityRepository = new IdentityRepository(_userManager.Object, null, null);
_identityService = new IdentityService(identityRepository);
FakeUserManager.cs:
public class FakeUserManager : UserManager<UserIdentity>
{
public FakeUserManager()
: base(new Mock<IUserStore<UserIdentity>>().Object,
new Mock<IOptions<IdentityOptions>>().Object,
new Mock<IPasswordHasher<UserIdentity>>().Object,
new IUserValidator<UserIdentity>[0],
new IPasswordValidator<UserIdentity>[0],
new Mock<ILookupNormalizer>().Object,
new Mock<IdentityErrorDescriber>().Object,
new Mock<IServiceProvider>().Object,
new Mock<ILogger<UserManager<UserIdentity>>>().Object)
{ }
}
Test method:
[TestMethod()]
public async Task GetUserAsyncTest()
{
//Arrange
//Act
var user = await _identityService.GetUserAsync(UserId4);
//Assert
Assert.AreEqual("pim#gmail.com", user.UserName);
}
Does anyone know a bypass / solution to my problem?
UPDATE: Stack trace:
EntityFrameworkQueryableExtensions.ExecuteAsync[TSource,TResult](MethodInfo operatorMethodInfo, IQueryable`1 source, Expression expression, CancellationToken cancellationToken)
EntityFrameworkQueryableExtensions.ExecuteAsync[TSource,TResult](MethodInfo operatorMethodInfo, IQueryable`1 source, CancellationToken cancellationToken)
EntityFrameworkQueryableExtensions.SingleOrDefaultAsync[TSource](IQueryable`1 source, CancellationToken cancellationToken)
IdentityRepository.GetUserAsync(Nullable`1 userId) line 55
IdentityService.GetUserAsync(Nullable`1 id) line 172
IdentityServiceTests.GetUserAsyncTest() line 102
ThreadOperations.ExecuteWithAbortSafety(Action action)
and the method GetUserAsync in the repository:
public async Task<UserIdentity> GetUserAsync(Guid? userId)
{
return await _userManager.Users.Where(x => x.Id.Equals(userId)).SingleOrDefaultAsync();
}
Though I am pretty late but after struggling with this error thought should post my bit too.
In my case, a package MockQueryable.Moq(https://www.nuget.org/packages/MockQueryable.Moq/) was being used, upgrading which solved this problem.
The _users sequence needs a provider that implements IAsyncQueryProvider. Couple of ways you can do it, the following is a mocked implementation.
Firstly, some scaffolding based on your OP:
public class UserIdentity : IdentityUser<Guid>
{
public int Score { get; set; }
}
public class IdentityRepository
{
readonly UserManager<UserIdentity> _userManager;
public IdentityRepository(UserManager<UserIdentity> userManager)
{
_userManager = userManager;
}
public async Task<UserIdentity> GetUserAsync(Guid? userId)
{
return await _userManager.Users.SingleOrDefaultAsync(x => x.Id.Equals(userId));
}
}
Create your mocked IAsyncQueryProvider and add it to your own IQueryable<UserIdentity>:
var user1 = new UserIdentity() { Id = Guid.NewGuid(), UserName = "foo#bar.com", Score = 1 };
var user2 = new UserIdentity() { Id = Guid.NewGuid(), UserName = "bar#baz.com", Score = 2 };
var user3 = new UserIdentity() { Id = Guid.NewGuid(), UserName = "tony stark", Score = 3000 };
var dataSource = new List<UserIdentity> { user1, user2, user3 }.AsQueryable();
var providerMock = new Mock<IAsyncQueryProvider>();
providerMock.Setup(x => x.ExecuteAsync<Task<UserIdentity>>(It.IsAny<Expression>(), It.IsAny<CancellationToken>()))
.Returns((Expression providedExpression, CancellationToken providedCancellationToken) => Task.FromResult(dataSource.Provider.Execute<UserIdentity>(providedExpression)));
var usersMock = new Mock<IQueryable<UserIdentity>>();
usersMock.Setup(x => x.ElementType).Returns(dataSource.ElementType);
usersMock.Setup(x => x.Expression).Returns(dataSource.Expression);
usersMock.Setup(x => x.Provider).Returns(providerMock.Object);
...
userManagerMock.Setup(x => x.Users).Returns(() => usersMock.Object);
You need a way to set the IQueryable<T> provider, the above is just one way you can do it.
If we pull this all together into a working LINQPad sample:
void Main()
{
var user1 = new UserIdentity() { Id = Guid.NewGuid(), UserName = "foo#bar.com", Score = 1 };
var user2 = new UserIdentity() { Id = Guid.NewGuid(), UserName = "bar#baz.com", Score = 2 };
var user3 = new UserIdentity() { Id = Guid.NewGuid(), UserName = "tony stark", Score = 3000 };
var dataSource = new List<UserIdentity> { user1, user2, user3 }.AsQueryable();
var providerMock = new Mock<IAsyncQueryProvider>();
providerMock.Setup(x => x.ExecuteAsync<Task<UserIdentity>>(It.IsAny<Expression>(), It.IsAny<CancellationToken>()))
.Returns((Expression providedExpression, CancellationToken providedCancellationToken) => Task.FromResult(dataSource.Provider.Execute<UserIdentity>(providedExpression)));
var usersMock = new Mock<IQueryable<UserIdentity>>();
usersMock.Setup(x => x.ElementType).Returns(dataSource.ElementType);
usersMock.Setup(x => x.Expression).Returns(dataSource.Expression);
usersMock.Setup(x => x.Provider).Returns(providerMock.Object);
var userManagerMock = new Mock<UserManager<UserIdentity>>
(new Mock<IUserStore<UserIdentity>>().Object,
new Mock<IOptions<IdentityOptions>>().Object,
new Mock<IPasswordHasher<UserIdentity>>().Object,
new IUserValidator<UserIdentity>[0],
new IPasswordValidator<UserIdentity>[0],
new Mock<ILookupNormalizer>().Object,
new Mock<IdentityErrorDescriber>().Object,
new Mock<IServiceProvider>().Object,
new Mock<ILogger<UserManager<UserIdentity>>>().Object);
userManagerMock.Setup(x => x.Users).Returns(() => usersMock.Object);
var identityRepository = new IdentityRepository(userManagerMock.Object);
var result = identityRepository.GetUserAsync(user2.Id).Result;
Console.WriteLine(result);
}
public class UserIdentity : IdentityUser<Guid>
{
public int Score { get; set; }
}
public class IdentityRepository
{
readonly UserManager<UserIdentity> _userManager;
public IdentityRepository(UserManager<UserIdentity> userManager)
{
_userManager = userManager;
}
public async Task<UserIdentity> GetUserAsync(Guid? userId)
{
return await _userManager.Users.SingleOrDefaultAsync(x => x.Id.Equals(userId));
}
}
we get the desired result:
I've left out your IdentityService in the above as essentially it's a detail to the answer; you just need to get a working, mocked UserManager. For my mock libraries, in particular EntityFrameworkCore.Testing, I'd use a concrete IAsyncQueryProvider rather than a mock; follow the link for an example should you want to go down that path.

Testing filters with IDependencyScope in Web API

I have WebApi simple NUnit Test
[Test]
public async Task Test()
{
var attribute = new TestAuthenticationAttribute {ApiVersions = new[] {"v1"}};
System.Web.Http.Controllers.HttpActionContext context = CreateExecutingContext();
var executedContext = new HttpAuthenticationContext(context, null);
const string reasonPhrase = "ReasonPhrase";
const string messagePhrase = "MessagePhrase";
executedContext.ErrorResult = new AuthenticationFailureResult(reasonPhrase, messagePhrase, executedContext.Request);
await attribute.AuthenticateAsync(executedContext, CancellationToken.None);
var errorResult = await executedContext.ErrorResult.ExecuteAsync(new CancellationToken());
Assert.AreEqual(HttpStatusCode.Unauthorized, errorResult.StatusCode);
}
private System.Web.Http.Controllers.HttpActionContext CreateExecutingContext()
{
return new System.Web.Http.Controllers.HttpActionContext { ControllerContext = new HttpControllerContext {Request = new HttpRequestMessage()
{
RequestUri = new Uri("http://TestApi/api/v1/Test")
}}};
}
and in TestAuthenticationAttribute I have
if (context.Request.GetDependencyScope().GetService(typeof(IExternalService)) is IExternalService externalService)
Do some actions;
How to set/resolve IExternalService dependency in test? Do I need e.g. UnityContainer or I can do it without container?
I added HttpConfiguration to my HttpActionContext and now Context.Request.GetDependencyScope() doesn't throw System.NullReferenceException. Of cource ontext.Request.GetDependencyScope().GetService(typeof(IExternalService)) is null, but now It's ok for my tests.
private System.Web.Http.Controllers.HttpActionContext CreateExecutingContext()
{
var config = new HttpConfiguration();
var httpActionContext = new System.Web.Http.Controllers.HttpActionContext
{
ControllerContext = new HttpControllerContext
{
Request = new HttpRequestMessage()
{
RequestUri = new Uri("http://TestApi/api/v1/Test"),
},
Configuration = config
}
};
httpActionContext.ControllerContext.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
return httpActionContext;
}
If I want to resolve dependency, I will can add DependencyResolver to my config or Mocking framework

Mock MVC WebViewPage using Moq

I would like to mock a WebViewPage and compare the output with an expected result.
here are my mockhelpers I'm using
public static class MockHelpers
{
public static HttpContextBase MockHttpContext(NameValueCollection queryStringCollection = null)
{
var request = new Mock<HttpRequestBase>(MockBehavior.Strict);
if(queryStringCollection != null)
SetupMockRequestQuerystringValues(request, queryStringCollection);
request.SetupGet(x => x.ApplicationPath).Returns("/");
request.SetupGet(x => x.Url).Returns(new Uri("http://localhost/a", UriKind.Absolute));
request.SetupGet(x => x.ServerVariables).Returns(new System.Collections.Specialized.NameValueCollection());
var response = new Mock<HttpResponseBase>(MockBehavior.Strict);
response.Setup(x => x.ApplyAppPathModifier(Moq.It.IsAny<String>())).Returns((String url) => url);
// response.SetupGet(x => x.Cookies).Returns(new HttpCookieCollection()); // This also failed to work
var context = new Mock<HttpContextBase>(MockBehavior.Strict);
context.SetupGet(x => x.Request).Returns(request.Object);
context.SetupGet(x => x.Response).Returns(response.Object);
context.SetupGet(x => x.Response.Cookies).Returns(new HttpCookieCollection()); // still can't call the Clear() method
context.SetupGet(p => p.User.Identity.Name).Returns("blah");
context.SetupGet(p => p.User.Identity.IsAuthenticated).Returns(true);
return context.Object;
}
private static void SetupMockRequestQuerystringValues( Mock<HttpRequestBase> request, NameValueCollection queryStringCollection)
{
request.SetupGet(x => x.QueryString).Returns(queryStringCollection);
}
public static ViewContext MockViewContext()
{
return CreateSimpleGenericMock<ViewContext>();
}
public static T MockWebViewPage<T>() where T : WebViewPage
{
var mock = new Mock<T>(MockBehavior.Loose) { CallBase = true };
mock.SetupGet(x => x.Context).Returns(MockHttpContext());
mock.SetupGet(x => x.Layout).Returns("layoutName");
mock.SetupGet(x => x.VirtualPath).Returns("virtualPathName");
mock.SetupGet(x => x.Page).Returns(new object{});
mock.SetupGet(x => x.PageData).Returns(new Dictionary<object, dynamic>()
{
{new object(), new object()}
});
var page = mock.Object;
//var helper = new HtmlHelper<object>(new ViewContext { ViewData = CreateSimpleGenericMock<ViewDataDictionary>() }, page, CreateSimpleGenericMock<RouteCollection>());
var helper = new HtmlHelper<object>(new ViewContext { ViewData = new ViewDataDictionary() }, page, new RouteCollection());
page.ViewContext = MockViewContext();
page.Html = helper;
return page;
}
public static T CreateSimpleGenericMock<T>() where T : class
{
var mock = new Mock<T>();
return mock.Object;
}
}
In the MockWebViewPage method you can see all that I have faked. My test method looks like so
[TestMethod]
public void TestMethod1()
{
var coreMasterTestClass = MockHelpers.MockWebViewPage<CoreMaster<object>>();
coreMasterTestClass.ExecutePageHierarchy();
var output = coreMasterTestClass.Html;
}
Is it possible to test the output that will be generated with mocking, and if not does anyone have any possible clues how I could test this. Please note that I'm not testing actual chstml pages but core pages within our own framework.

How can I mock ServiceStack IHttpRequest

I'm trying to get a unit test working for a service that is injecting items into the IHttpRequest.Items, using a request filter:
this.RequestFilters.Add((req, res, dto) =>
{
// simplified for readability...
var repo = container.Resolve<IClientRepository>();
var apiKey = req.Headers["ApiKey"];
// lookup account code from api key
var accountcode = repo.GetByApiKey(apiKey);
req.Items.Add("AccountCode", accountCode);
});
My service uses that dictionary item:
public class UserService : AppServiceBase
{
public IUserServiceGateway UserServiceGateway { get; set; }
public object Any(UserRequest request)
{
var accountCode = base.Request.Items["AccountCode"].ToString();
var user = UserServiceGateway.GetUserByUsername(request.Name);
return new UserResponse { User = user };
}
}
My test needs be somehow to mock the request, and insert that account code item:
[Test]
public void ValidUsernameReturnUser()
{
// arrange
var gateway = new Mock<IUserServiceGateway>();
gateway.Setup(s => s.GetUserByUsername(It.IsAny<string>()))
.Returns(new UserAccountDTO { Forename = "John", Surname = "Doe" });
var service = new UserService {
UserServiceGateway = gateway.Object,
RequestContext = new MockRequestContext(),
//Request = has no setter
};
// request is this case is null
base.Request.Items.Add("AccountCode", "DEF456");
// act
var response = (UserResponse)service.Any(new UserRequest { Name = "test" });
// assert
Assert.That(response.Result, Is.Not.Null);
}
The service itself accepts a mocked RequestContext, but not a Request. The test therefore fails. Is there a better way to do this?
I think this should do it.
[Test]
public void ValidUsernameReturnUser()
{
// arrange
var mockRequestContext = new MockRequestContext();
//add items to Request
mockRequestContext.Get<IHttpRequest>().Items.Add("AccountCode", "DEF456");
var gateway = new Mock<IUserServiceGateway>();
gateway.Setup(s => s.GetUserByUsername(It.IsAny<string>()))
.Returns(new UserAccountDTO { Forename = "John", Surname = "Doe" });
var service = new UserService {
UserServiceGateway = gateway.Object,
RequestContext = new MockRequestContext(),
};
// act
var response = (UserResponse)service.Any(new UserRequest { Name = "test" });
// assert
Assert.That(response.Result, Is.Not.Null);
}