How can I redeem a ServiceStack IHttpRequest

I am trying to get a unit test for a service that injects elements into IHttpRequest.Items objects using a query 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 this dictionary element:

 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 should somehow mock the request and insert this element of the account code:

 [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 laughed RequestContext, but not Request. Therefore, the test fails. Is there a better way to do this?

+4
source share
1 answer

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); } 
+4
source

Source: https://habr.com/ru/post/943635/


All Articles