【发布时间】:2017-03-10 17:34:05
【问题描述】:
我正在尝试使用从我的 [ClassInitialize](MS 测试)方法调用的 Owin 内存服务器对我的 WebApi 控制器进行单元测试。我需要通过 DI 容器将我的存储库对象 IFourSquareRepository 的模拟实例注入到我的控制器中。当测试类 [ClassInitialize] 方法执行时,Owin 服务器设置、静态 Ninject IKernel 实例及其绑定在 WebApi 项目中的 Owin 配置类中处理:
kernel.Bind<IFourSquareRepository>().ToMethod(
context =>
{
return MockRepository.GenerateMock<IFourSquareRepository>();
// This block runs only once ...
// But stubs from the test method return null when the test call
// fires up the controller ...
}
).InSingletonScope();
当在我的测试项目的测试方法中进行评估时,这些存根可预测地工作(即:它们返回我在下面的存根定义中指定的值)。
我的 [TestMethod] 案例为我的控制器所依赖的模拟接口 (IFourSquareRepository) 的方法创建存根,并调用解析到我的 WebApi 上的 WebApi 端点控制器如下所示 - (当我发送 HttpClient 请求时,我无法手动将我的模拟对象注入控制器实例 - 我依靠 WebApi 管道来创建控制器实例,所以我必须使用 DI 容器来注入一个模拟的 IFourSquareRepository 对象到控制器中):
[TestMethod]
public void Test1_InMemServer()
{
var testRet = new BookmarkedPlace() { Id = 99 };
string userName = "Joe";
this.MockRepository.Stub(
repo => repo.GetFirstBookmarkedPlace()).Return(testRet);
// stub for test Repo IF method
// Act User the base class static HttpClient to talk to the Owin-hosted WebApi
var response = InMemoryTest.HttpClient.GetAsync( string.Format("/api/places/{0}", userName) ).Result;
var body = response.Content.ReadAsStringAsync().Result;
// Assert
Assert.IsTrue(response.IsSuccessStatusCode, "Request Failed ");
}
我的问题是,无论我做什么,当控制器(从我上面的 HttpClient 请求中调用)调用存根方法时,它总是返回 NULL !!
public IEnumerable<BookmarkedPlace> Get(string userName, int page = 0, int pageSize = 10)
{
IQueryable<BookmarkedPlace> query;
query = this.Repository.GetFirstBookmarkedPlace();
// Mock Repo call returning null !
// Other stuff goes here ...
return results;
}
这几天我一直在思考这个问题 - 有什么想法吗?
【问题讨论】:
标签: asp.net-web-api ninject owin rhino-mocks