使用ServiceStack(v5.5.0(我读到通过控制器调用服务的推荐方法是使用网关。完整示例位于https://github.com/RhysWilliams647/ServiceStackControllerTest
public class HomeController : ServiceStackController
{
public ActionResult Index()
{
var response = Gateway.Send<TestServiceResponse>(new TestServiceRequest());
IndexModel model = new IndexModel { Message = response.Message };
return View(model);
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
然而,当通过xUnit测试我的控制器时,我得到了一个null异常错误,因为Gateway为null。下面是我的AppHost
public class AppHost : AppSelfHostBase
{
public AppHost() : base("Test", typeof(TestService).Assembly)
{
}
public override IServiceGateway GetServiceGateway(IRequest req) =>
base.GetServiceGateway(req ?? new BasicRequest());
public override void Configure(Container container)
{
SetConfig(new HostConfig
{
HandlerFactoryPath = "api"
});
container.RegisterFactory<HttpContext>(() => HttpContext.Current);
// register container for mvc
ControllerBuilder.Current.SetControllerFactory(new FunqControllerFactory(container));
}
}
我的测试
[Trait("Category", "Controllers")]
[Collection("AppHostFixture")]
public class ControllerTest
{
[Fact]
public void CanCallHomeControllerIndex()
{
var controller = new HomeController();
controller.Index();
}
}
有人能建议如何测试调用服务网关的ServiceStackController吗?
AppSelfHostBase
是一个HttpListener自主机,它不支持MVC,因此您将无法运行任何集成测试。
当你新建一个MVC控制器实例时,如下所示:
var controller = new HomeController();
ServiceStackController
所需的base.HttpContext
不存在,它需要ASP.NET HttpContext,但单元测试中的自宿主正在自宿主HttpListener服务器上运行。
您可以尝试通过HostContext
单例访问网关,即:
var gateway = HostContext.AppHost.GetServiceGateway(new BasicRequest());
var response = gateway.Send<TestServiceResponse>(new TestServiceRequest());
在这个例子中,它用一个模拟HttpRequestContext调用Gateway来模拟一个请求,但您无法用自托管的HttpListener执行真正的MVC集成测试。