I have webapi which for testing purposes I am hosting in owin. I have set it up using autofac. now when I am testing I want to inject moq dependencies. which I am not able to so far. I have read the documentation and did bit of research but I am missing something.
here is the testing code.
[Test]
public void Request_all_airports()
{
const int port = 8086;
AirportCollection moqAirportCollection = new AirportCollection();
moqAirportCollection.Airports = new List<Airport>{new Airport{IATA = "moq",Name = "moqName"}};
using (WebApp.Start<Startup>("http://localhost:" + port))
{
using (var mock = AutoMock.GetLoose())
{
var moqObj = mock.Mock<IAirportService>().Setup(x => x.GetAirports()).Returns(moqAirportCollection);
var client = new HttpClient {BaseAddress = new Uri("http://localhost:" + port)};
var response = client.GetAsync("/api/airport/get").Result;
var body = response.Content.ReadAsStringAsync().Result;
var airportCollection = JsonConvert.DeserializeObject<AirportCollection>(body);
}
}
}
Please have a look. let me know what I am missing. if you want to look at controller code or any other piece do let me know .
here is code for startup
public class Startup
{
public static IContainer container { get; set; }
public void Configuration(IAppBuilder appBuilder)
{
var httpConfig = new HttpConfiguration();
container = AutofacSetup.Register(httpConfig);
WebApiConfig.Register(httpConfig);
appBuilder.UseAutofacMiddleware(container);
appBuilder.UseAutofacWebApi(httpConfig);
appBuilder.UseWebApi(httpConfig);
}
}
Thanks
I think so I have solved it with help from people. here is my code.
var moq = new Mock<IAirportService>();
moq.Setup(x => x.GetAirports()).Returns(moqAirportCollection);
newBuilder.RegisterInstance(moq.Object).As<IAirportService>();
newBuilder.Update(Startup.container);
I havnt rebuild the contrain i just updated it. autofac have behavior to use latest registration so it will use mocked on here.
You are almost there.
In your test you need to register your mock service with your autofac container so that dependencies on IAirportService are resolved with the mock in the application.
One way to achieve this is override the Startup class' Configuration method for each test and put your test DI in there. I've put some comments below to show changes that can be made:
public class Startup
{
public static IContainer container { get; set; }
// make this virtual
public virtual void Configuration(IAppBuilder appBuilder)
{
var httpConfig = new HttpConfiguration();
// have this return the ContainerBuilder instead of the container
var builder = AutofacSetup.Register(httpConfig)
container = builder.Build();
WebApiConfig.Register(httpConfig);
appBuilder.UseAutofacMiddleware(container);
appBuilder.UseAutofacWebApi(httpConfig);
appBuilder.UseWebApi(httpConfig);
}
}
Then in your test class, derive from the Startup class and put your test logic in. Something like this:
public class MyTestCase {
public static Mock<IAirportService> MockObj { get; set; }
private class TestStartup : Startup {
public override void Configuration(IAppBuilder app) {
var httpConfig = new HttpConfiguration();
// this now returns ContainerBuilder instead of the container
var builder = AutofacSetup.Register(httpConfig)
// register your mock, change this to whatever lifetime scope you need
var moqAirportCollection = new AirportCollection();
moqAirportCollection.Airports = new List<Airport>{new Airport{IATA = "moq",Name = "moqName"}};
var mock = AutoMock.GetLoose()
MockObj = mock.Mock<IAirportService>()
.Setup(x => x.GetAirports())
.Returns(moqAirportCollection);
var moqObj = MockObj.Object;
builder.RegisterInstance(moqObj).As<IAirportService>();
container = builder.Build();
WebApiConfig.Register(httpConfig);
appBuilder.UseAutofacMiddleware(container);
appBuilder.UseAutofacWebApi(httpConfig);
appBuilder.UseWebApi(httpConfig);
}
}
[Test]
public void Request_all_airports()
{
using (var server = WebApp.Start<Startup>())
{
var response =
server.CreateRequest("/api/airport/get")
.GetAsync()
.Result;
var body = response.Content.ReadAsStringAsync().Result;
var result = JsonConvert.DeserializeObject<AirportCollection>(body);
// assert something
}
}
}
A unit test should test a single component. In your case, you are trying to test the AirportController through a HTTP query, not the AirportController as a standalone component.
The AirportController class depends on a IAirportService component. In order to test the component without any dependency you created a moq on IAirportService. Now you can instantiate a new AirportController with this moq and run your test using this instance.
If you have a AirportController like this
public class AirportController
{
public AirportController(IAirportService airportService) { /* ... */}
}
The AirportController test should be like this :
[Test]
public void Request_all_airports()
{
AirportCollection moqAirportCollection = new AirportCollection();
var moqAirPort = new Airport{ IATA = "moq",Name = "moqName" };
moqAirportCollection.Airports = new List<Airport>{ moqAirPort };
using (var mock = AutoMock.GetLoose())
{
var moqAirportService = mock.Mock<IAirportService>()
.Setup(x => x.GetAirports())
.Returns(moqAirportCollection);
var testedAirportController = new AirportController(moqAirportService);
AirportCollection airportCollection = testedAirportController.Get();
Assert.AreEquals(1, airportCollection.Length, "Invalid number of airport");
Assert.AreEquals(moqAirPort.Name, airportCollection[0].Name, "Invalid name");
}
}
Related
I'm using the Mediatr library to register and call my RequestHandlers.
Everything went fine until I started reading more about integrated tests.
PLEASE READ AFTER EDIT
I can't call my class which inherits from the RequesHandler.
My class looks like this:
public class MyRequestHandler : RequestHandler<MyRequest, MyResponse>
{
....
}
I'm not using the Meditr async and I'm using .net framework 4.7 instead of asp.net core, so, everything looks like returns me answers for asp.net core.
When I construct MyTestClass, to construct the RequestHandler I have to create a ServiceFactory and maybe this is the problem because I don't know how.
public MyClassTest()
{
ServiceFactory sv = null;
_mediator = new Mediator(sv);
}
EDIT
Providing more info
I have this Handler in my Application Layer
public class LogInUserByFormHandler : RequestHandler<LogInUserByFormRequest, LogInUserByFormResponse>
{
private readonly IValidator<LogInUserByFormRequest> _validator;
public LogInUserByFormHandler(IValidator<LogInUserByFormRequest> validator)
{
_validator = validator;
}
protected override LogInUserByFormResponse Handle(LogInUserByFormRequest request)
{
_validator.ValidateAndThrow(request);
var userInfo = GetUserInfo(request);
ValidateLogInUserByFormRules(userInfo);
var userLoginInfo = GetValidUserLoginInfo(request);
ValidateUserLoginInfoByFormRules(userLoginInfo);
var sessionKey = CreateUserSessionKey(userInfo);
var response = new LogInUserByFormResponse
{
UserName = request.UserName,
SessionKey = sessionKey,
UserId = userInfo.id_usuario
};
return response;
}
//A LOT OF CODE HERE, methods and etc
}
As it's possible to see, it implements the Mediatr.
On my Web Project on Presentation Layer, I used AutoFac to Inject the Handlers, so, any Request I do is always handled by the right method.
All I have to do is call, like this:
var logInByFormRequest = new LogInUserByFormRequest
{
UserName = viewModel.UserName,
Password = viewModel.Password
};
var response = _mediator.Send(logInByFormRequest).Result;
This works like a charm. The problem now is on the Test project. It references the Application as the Presentation Project does.
I don't know how to make the mediator.send find the right method.
EDIT²
Here comes my test code
[TestClass]
public class LogInUserByFormTest
{
private LogInUserByFormRequest CreateRequest(string userName, string password)
{
LogInUserByFormRequest request = new LogInUserByFormRequest
{
UserName = userName,
Password = password
};
return request;
}
[TestMethod]
[Description("")]
public void UserName_ShouldHave_Max_30Characters_Exception()
{
try
{
var request = CreateRequest("UserNameIsGreaterThanAllowed", "password");
var mediator = new Mock<IMediator>();
var response = mediator.Object.Send(request).Result;
}
catch (System.Exception ex)
{
throw;
}
}
}
The result (response) is always null and the mediator doesn't call the right handler.
EDIT3
Here is how I register the handlers and validators.
I use autofac. This class here is called on the global.asax
public class AutofacConfig
{
public static void ConfigureContainer()
{
var builder = new ContainerBuilder();
builder.RegisterControllers(Assembly.GetExecutingAssembly()).InstancePerRequest();
builder.RegisterType<Mediator>().As<IMediator>().InstancePerLifetimeScope();
builder.RegisterType<AutofacValidatorFactory>().As<IValidatorFactory>().SingleInstance();
builder.RegisterType<FluentValidationModelValidatorProvider>().As<ModelValidatorProvider>();
builder.RegisterType<RegistryManagerService>().As<IRegistryManagerService>().SingleInstance().WithParameter("appName", ConfigurationManager.AppSettings["APPNAME"]);
builder.Register<ServiceFactory>(context =>
{
var c = context.Resolve<IComponentContext>();
return t => c.Resolve(t);
});
builder.RegisterAssemblyTypes(Assembly.Load("Docspider.Application"))
.Where(x => x.Name.EndsWith("Handler"))
.AsImplementedInterfaces();
builder.RegisterAssemblyTypes(Assembly.Load("Docspider.Application"))
.Where(x => x.Name.EndsWith("Validator"))
.AsImplementedInterfaces()
.InstancePerLifetimeScope();
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
}
public class AutofacValidatorFactory : ValidatorFactoryBase
{
private readonly IComponentContext _context;
public AutofacValidatorFactory(IComponentContext context)
{
_context = context;
}
public override IValidator CreateInstance(Type validatorType)
{
if (_context.TryResolve(validatorType, out object instance))
{
var validator = instance as IValidator;
return validator;
}
return null;
}
}
For such an integration test you would need to configure the necessary dependencies. Since you have indicated that Autofac is being used then configure a container just as you would have in production. Use the container to get the mediator and perform the desired test.
For example.
[TestClass]
public class LogInUserByForm_IntegrartionTest {
private LogInUserByFormRequest CreateRequest(string userName, string password) {
LogInUserByFormRequest request = new LogInUserByFormRequest {
UserName = userName,
Password = password
};
return request;
}
IMediator BuildMediator() {
//AutoFac
var builder = new ContainerBuilder();
builder.RegisterAssemblyTypes(typeof(IMediator).GetTypeInfo().Assembly).AsImplementedInterfaces();
var mediatrOpenTypes = new[] {
typeof(IRequestHandler<,>)
};
foreach (var mediatrOpenType in mediatrOpenTypes) {
builder
.RegisterAssemblyTypes(typeof(LogInUserByFormRequest).GetTypeInfo().Assembly)
.AsClosedTypesOf(mediatrOpenType)
.AsImplementedInterfaces();
}
builder.Register<ServiceFactory>(ctx => {
var c = ctx.Resolve<IComponentContext>();
return t => c.Resolve(t);
});
//...all other needed dependencies.
//...
var container = builder.Build();
var mediator = container.Resolve<IMediator>();
return mediator;
}
[TestMethod]
[Description("")]
public async Task UserName_ShouldHave_Max_30Characters_Exception() {
try
{
//Arrange
var request = CreateRequest("UserNameIsGreaterThanAllowed", "password");
var mediator = BuildMediator();
//Act
var response = await mediator.Send(request);
//Assert
//...assert the expected values of response.
}
catch (System.Exception ex)
{
throw;
}
}
}
The above was modeled after the examples provided by MediatR.Examples.Autofac
I an getting the below issue when running the Unit Test project.
Unable to get Default Constructor For class ********
[TestClass]
public class PersonRegistration
{
private ILoggingService _loggingService;
private IUserManager _userManager;
public PersonRegistration(IUserManager userManager, ILoggingService loggingService)
{
this._userManager = userManager;
this._loggingService = loggingService;
}
[TestMethod]
public void TestMethod1()
{
RegisterBindingModel model = new RegisterBindingModel();
AccountController ac = new AccountController(_userManager, _loggingService);
model.UserName = "test123#gmail.com";
var result = ac.Register(model);
Assert.AreEqual("User Registered Successfully", result);
}
How to fix that. Some answers says that to use a parameter less constructor. But here I need params.
RegisterBindingModel()
public class RegisterBindingModel
{
public RegisterBindingModel();
[Display(Name = "User name")]
[Required]
public string UserName { get; set; }
}
Issue
I've just tested this in my unit tests.
Add
public PersonRegistration()
{
}
And it should run fine.
There is no need for constructors on your unit test classses. If you are using a mocking framework like Moq then I use a factory to return the dependent moqs for the classes I'm testing.
public ILoggingService ReturnMockLoggingService()
{
var mockService = new Mock<ILoggingService>();
return mockService.Object;
}
Then in the test fixture.
[TestMethod]
public void TestMethod1()
{
RegisterBindingModel model = new RegisterBindingModel();
var logService = MockFactory.ReturnMockLoggingService();
var userService = MockFactory.ReturnMockUserService();
AccountController ac = new AccountController(userService, logService);
model.UserName = "test123#gmail.com";
var result = ac.Register(model);
Assert.AreEqual("User Registered Successfully", result);
}
if you're not using mocks then simply instance the user and log service in the test or create a SetUp.
[ClassInitialize]
public void SetUp()
{
_loggingService = new LoggingService();
_userManager = new UserManager();
}
Hope that helps.
You should use a mocking framework like Moq.
Example:
[TestClass]
public class PersonRegistration
{
[TestMethod]
public void TestMethod()
{
RegisterBindingModel model = new RegisterBindingModel();
var mockService = new Mock<ILoggingService>();//Mock
//Do something as per your requirement
//var reg= new List<RegisterBindingModel >(); // provide some sample list
//mockService .Setup(r => r.GetAll=()).Return(reg);
var mockManager = new Mock<IUserManager>();//Mock
//Do something as per your requirement
//var user= new List<User>(); // provide some sample list
//mockManager .Setup(r => r.GetAll=()).Return(user);
AccountController ac = new AccountController(mockManager.Object, mockService.Object);
model.UserName = "test123#gmail.com";
var result = ac.Register(model);
Assert.AreEqual("User Registered Successfully", result);
}
}
You can get help form this and this link.
I have an http client wrapper that I'm injecting into all my controllers. If a user is authenticated, the injected wrapper should have some properties set with the authenticated user information.
I currently have this:
[System.Web.Mvc.Authorize]
public class ProfileController : Controller
{
private readonly IMyClient client;
public ProfileController()
{
string apiKey = ConfigurationManager.AppSettings["ApiKey"];
client = new MyClient(apiKey);
SetupClient();
}
private void SetupClient()
{
if (Thread.CurrentPrincipal.Identity.IsAuthenticated)
{
var identity = Thread.CurrentPrincipal.Identity as ClaimsIdentity;
var tokenClaim = identity.Claims.First(c => c.Type == ClaimTypes.Sid);
client.AddCredentials(tokenClaim.Value);
}
}
}
I would like to offload SetupClient to somewhere that will allow me to do dependency injection of IMyClient.
Essentially I want to implement this solution:
ProfileController.cs
[System.Web.Mvc.Authorize]
public class ProfileController : Controller
{
private readonly IMyClient client;
public ProfileController(IMyClient client)
{
this.client = client;
}
}
Startup.cs
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
IoCConfig.RegisterIoC(app);
ConfigureAuth(app);
}
}
IoCConfig.cs
public class IoCConfig
{
public static void RegisterIoC(IAppBuilder app)
{
var container = new Container();
container.Register<IMyClient>(
() =>
{
var apiKey = ConfigurationManager.AppSettings["APIKey"];
var myClient= new MyClient(apiKey);
// This will not work as this code is executed on app start
// The identity will not be of the user making the web request
var identity = Thread.CurrentPrincipal.Identity as ClaimsIdentity;
var tokenClaim = identity.Claims.First(c => c.Type == ClaimTypes.Sid);
client.AddCredentials(tokenClaim.Value);
return myClient;
});
// Register the dependency resolver.
DependencyResolver.SetResolver(
new SimpleInjectorDependencyResolver(container));
}
}
I'm stuck in the code for IoCConfig to extract information of the authenticated user (if the user is authenticated) and setup the client for injection. Any help here?
My IoC framework is SimpleInjector but I'd like an agnostic solution.
This is how I would do it
public class ProfileController : Controller
{
private readonly MyClient _client;
public ProfileController()
{
var clientInfo = Resolve<IClientInfo>(); // call out to your service locator
_client = clientInfo.GetClient();
}
}
public interface IClientInfo
{
MyClient GetClient();
}
public interface IAuth
{
System.Security.Claim GetSidClaim();
}
public class ClientInfo : IClientInfo
{
private readonly IAuth _auth;
public ClientInfo(IAuth auth)
{
_auth = auth;
}
public MyClient GetClient()
{
var apiKey = ApiKey;
var client = new MyClient(apiKey);
var claim = _auth.GetSidClaim();
client.AddCredentials(claim.Value);
return client;
}
protected virtual string ApiKey
{
get { return ConfigurationManager.AppSettings["APIKey"]; }
}
}
I'd take a look at NInject and the MVC extensions...
http://ninject.codeplex.com/wikipage?title=Dependency%20Injection%20With%20Ninject
http://www.codeproject.com/Articles/412383/Dependency-Injection-in-asp-net-mvc-and-webapi-us
When setup correctly it's just a matter of creating a binding for IMyClient NInject will implicitly inject it for you. There are lots of other injection frameworks out there, NInject is just the one I've chosen. Each of them will give you a substantial benefit over anything you could cook up on your own. e.g. with NInject you can create bindings that inject a singleton across your app or a binding that injects a singleton for each request.
In NInject you could create a binding something like
Bind<IMyClient>().ToMethod(x => SetupClient(x)).InRequestScope();
private IMyClient SetupClient(IContext context)
{
string apiKey = ConfigurationManager.AppSettings["ApiKey"];
var client = new MyClient(apiKey);
if (Thread.CurrentPrincipal.Identity.IsAuthenticated)
{
var identity = Thread.CurrentPrincipal.Identity as ClaimsIdentity;
var tokenClaim = identity.Claims.First(c => c.Type == ClaimTypes.Sid);
client.AddCredentials(tokenClaim.Value);
}
return client;
}
InRequestScope says that NInject should create a single instance for each request...
https://github.com/ninject/Ninject.Web.Common/wiki/InRequestScope
I think the equivalent in SimpleInjector is...
https://simpleinjector.codeplex.com/wikipage?title=ObjectLifestyleManagement#PerWebRequest
Is the answer as simple as changing your code to...
public static void RegisterIoC(IAppBuilder app)
{
var container = new Container();
container.RegisterPerWebRequest<IMyClient>(
() =>
{
...
I solved this by a version of what CRice posted by using a factory delegate:
ProfileController.cs
[System.Web.Mvc.Authorize]
public class ProfileController : Controller
{
private readonly IMyClient client;
public ProfileController(Func<IMyClient> clientFactory)
{
client = clientFactory.Invoke();
}
}
IoCConfig.cs
public class IoCConfig
{
public static void RegisterIoC(IAppBuilder app)
{
// Create the container as usual.
Container container = new Container();
// Registering as a factory delegate because we need the user authentication information if any.
container.RegisterSingle<Func<IMyClient>>(() =>
{
string apiKey = ConfigurationManager.AppSettings["ApiKey"];
var myClient = new MyClient(apiKey);
if (Thread.CurrentPrincipal.Identity.IsAuthenticated)
{
var identity = Thread.CurrentPrincipal.Identity as ClaimsIdentity;
var tokenClaim = identity.Claims.First(c => c.Type == ClaimTypes.Sid);
myClient.AddCredentials(tokenClaim.Value);
}
return myClient;
});
// This is an extension method from the integration package.
container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
// This is an extension method from the integration package as well.
container.RegisterMvcIntegratedFilterProvider();
container.Verify();
DependencyResolver.SetResolver(
new SimpleInjectorDependencyResolver(container));
}
}
I've setup 2 wcf services which are
PdfService.svc
and
MailService.svc
The MailService attaches a PDF generated by the PDFService ie
public void SendMail(ICommand command)
{
// how should I handle this in Unit Test (mocks with NSubstitute)
_service = new PdfService(_pdfSettings);
var request = new DownloadRequest {FileName = "form.pdf",
FormEntry = command.FormEntry };
var thefile = _service.DownloadFile(request);
sendEmail(command.Mail, thefile.FileByteStream);
}
I would like to know how to stub out the PdfService while testing the MailService, and is this a bad idea for communicating wcf to wcf?
Thanks!
You probably want to use Dependency Injection and Mock Objects.
The general idea is to pass the service to your method in the method call or object constructor. With the snippet you've provided, I'd rewrite it this way:
//Method Call
IPdfService mockService = new MockPdfService() // this is a mock that implements your interface
SendMail(cmd, mockService);
//Method
public void SendMail(ICommand command, IPdfService service)
{
// how should I handle this in Unit Test (mocks with NSubstitute)
_service = new PdfService(_pdfSettings);
var request = new DownloadRequest {FileName = "form.pdf",
FormEntry = command.FormEntry };
var thefile = service.DownloadFile(request);
sendEmail(command.Mail, thefile.FileByteStream);
}
In your mockService you can add diagnostic helps that you can then write Asserts against after the sendmail call to see what happened in your mock.
Probably the better way to do it though is to have your main class constructor take the service object and then rewrite your method call, something like this:
public class MyClass
{
private IPdfService _pdfService;
public MyClass()
{
_pdfService = new PdfService(_pdfSettings);
}
// Call this with your Mock pdfService
public MyClass(IPdfService pdfService)
{
_pdfService = pdfSerivce;
}
public void SendMail(ICommand command)
{
var request = new DownloadRequest { FileName = "form.pdf", FormEntry = command.FormEntry };
var thefile = _pdfService.DownloadFile(request);
sendEmail(command.Mail, thefile.FileByteStream)
}
}
I'd like to make my ServiceStack service testable.
Presently I have:
[RequireFormsAuthentication]
public object Delete(DeleteRequest request)
{
var originalRequest = (HttpRequest)Request.OriginalRequest;
var identity = originalRequest.RequestContext.HttpContext.User.Identity;
return othercode(identity);
}
Where RequireFormsAuthentication is
public class RequireFormsAuthenticationAttribute : RequestFilterAttribute
{
public override void Execute(IHttpRequest req, IHttpResponse res, object requestDto)
{
var originalRequest = (HttpRequest)req.OriginalRequest;
var identity = originalRequest.RequestContext.HttpContext.User.Identity;
if (!identity.IsAuthenticated)
{
res.StatusCode = (int)HttpStatusCode.Forbidden;
res.EndServiceStackRequest(skipHeaders: true);
}
}
}
I've mocked out all the dependencies used by 'othercode()' and all that's left is the stuff that's in the base class Service. Is there a pattern/strategy/approach/something I'm missing that makes this trivial?
Here's how to test with Moq. This service looks for a "key" and "value" in the query string and another parameter in the request DTO. The service returns a string response based on the value given.
[Test]
public void MyTest()
{
var mockRequestContext = new Mock<IRequestContext>();
var mockedHttpRequest = new Mock<IHttpRequest>();
NameValueCollection querystring = new NameValueCollection();
querystring.Add("myKey", "myValue");
mockedHttpRequest.SetupGet(r => r.QueryString).Returns(querystring);
mockRequestContext.Setup(x => x.Get<IHttpRequest>()).Returns(mockedHttpRequest.Object);
AboutService service = new AboutService
{
RequestContext = mockRequestContext.Object,
};
AboutResponse response = (AboutResponse)service.Any(new About
{
Company = "myOtherValue",
});
Assert.AreEqual(0, response.QueryResult);
Assert.AreEqual("validResponse", response.Version);
}
I apologize for not using moq...already had some of this done using RhinoMocks. I think the concept should transfer to moq. This might be a good resource as well as this this.
Anyway, I think the test code below should get you started. Your seam into mocking Request.OriginalRequest is replaceing the Service.RequestContext with a mock object. Then you just have to mock everything beyond that. It's going to be a lot of 'mocking' and if you repeat to yourself 'Are you mocking me' every time you mock a class it's almost enjoyable.
[Test]
public void testsomethign()
{
var mockedRequestContext = MockRepository.GenerateMock<IRequestContext>();
var mockedHttpRequest = MockRepository.GenerateMock<IHttpRequest>();
var mockedOriginalRequest = MockRepository.GenerateMock<HttpRequestBase>();
var mockedOriginalRequestContext = MockRepository.GenerateMock<RequestContext>();
mockedOriginalRequest.Stub(x => x.RequestContext).Return(mockedOriginalRequestContext);
mockedHttpRequest.Stub(x => x.OriginalRequest).Return(mockedOriginalRequest);
mockedRequestContext.Stub(x => x.Get<IHttpRequest>()).Return(mockedHttpRequest);
var service = new ServiceTests()
{
RequestContext = mockedRequestContext
};
service.Delete(new DeleteRequest());
}
Be sure to check out the namespace: ServiceStack.ServiceInterface.Testing.
In there you can find a MockRequestContext that you can use as follows:
var mockContext = new ServiceStack.ServiceInterface.Testing.MockRequestContext();
//do stuff to set it up if desired...
AboutService service = new AboutService
{
RequestContext = mockContext
};