我想爲我的ApiController編寫一些單元測試並遇到一些問題。如何在Web API中模擬Request.form
這裏是我的TestMethod的
[TestMethod]
public void CustomerController_AddUnitTest()
{
var custid = Guid.NewGuid();
var customers = new Customer() { CustomerName = "Enterprise", CustomerId = custid };
var rmContext = MockRepository.GenerateMock<HttpContextBase>();
var rmRequest = MockRepository.GenerateMock<HttpRequestBase>();
rmContext.Stub(x => x.Request).Return(rmRequest);
var FormData = new NameValueCollection { { "FirstName", "Jonathan" }, { "LastName", "Danylko" } };
rmRequest.Stub(r => r.Form).Return(FormData);
rmContext.Stub(p => p.Request).Return(rmRequest);
var forms = rmContext.Request.Form;
> // here i am able to get forms value but i couldn't pass these value
> to main controller
var mockRepository = MockRepository.GenerateMock<ICustomerService>();
mockRepository.Stub(x => x.Add(new Customer())).IgnoreArguments().Return(1);
_customerController = new CustomerController(mockRepository);
var result = _customerController.CustomerAdd();
Assert.IsNotNull(result);
}
這是我的控制器代碼看起來像
public int CustomerAdd()
{
var localhost = HttpContext.Current.Request.Url.Authority;
var formData = HttpContext.Current.Request.Form["FormData"];
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
var customer = json_serializer.Deserialize<Customer>(formData);
if (HttpContext.Current.Request.Files.Count > 0)
{
HttpPostedFile file = HttpContext.Current.Request.Files[0];
string fileName = customer.CustomerName.Trim() + "_" + file.FileName;
var filePath = HttpContext.Current.Server.MapPath(Constants.FileUploadImagePath + fileName);
file.SaveAs(filePath);
customer.Logo = fileName;
}
return _iCustomerService.Add(customer);
}
我想模擬數據傳遞給var formData = HttpContext.Current.Request.Form["FormData"];
任何人都可以有一個想法來解決這個問題我真的厭倦了這個任務。
被測方法設計不佳,與靜態依賴性緊密相關,這使得測試變得困難。儘量避免將你的代碼緊密耦合到'HttpContext'。 – Nkosi
是的,我知道。但我不知道如何模擬這一行代碼 –
var formData = HttpContext.Current.Request.Form [「FormData」]; –