我知道你不能用 moq 模拟静态方法,但我想知道我可能的选择是什么
我定义了一个控制器类
public class CustomerController : BaseController
{
private ICustomerManager cm;
public CustomerController()
: this(new CustomerManager())
{
}
public CustomerController(ICustomerManager customerMan)
{
cm = customerMan;
}
public ActionResult EditContact(ContactVM model, IEnumerable<HttpPostedFileBase> Files, PageAction pageAction)
{
if (ModelState.IsValid)
{
InitializeContactVM(model); //throws an error
}
}
private void InitializeContactVM(ContactVM model)
{
model.Customer = cm.GetViewFindCustomerDetails((int)model.CustomerId);
model.ContactClassificationList = AddBlankToList(SelectLists.ContactClassifications(false));
model.ContactSourceList = AddBlankToList(SelectLists.ContactSources(false));
}
}
我的单元测试如下所示:
public void Edit_Contact_Update_Existing_Contact()
{
var dataManager = new Mock<IReferenceDataManager>();
//dataManager.Setup(a=>a.GetContactClassifications()).Returns()
var contact = InitializeContact();
var contactvm = new ContactVM(contact);
var fileMock = new Mock<HttpPostedFileBase>();
var files = new[] {fileMock.Object};
var mocManager = InitializeMocManagerContact();
mocManager.Setup(a => a.GetContactById(It.IsAny<int>())).Returns(contact);
mocManager.Setup(a => a.UpdateContact(It.IsAny<ContactVM>(), It.IsAny<string>())).Returns(contact);
var controller = new CustomerController(mocManager.Object);
var controllerContext = InitializeContext();
controller.ControllerContext = controllerContext.Object;
// mocManager.CallBase = true;
var result = controller.EditContact(contactvm, files, PageAction.Default) as ViewResult;
var model = result.ViewData.Model as ContactVM;
Assert.IsTrue(model.ContactId == contact.CONTACT_ID);
}
问题出在调用 SelectLists.ContactClassifications(false) 的私有方法中,然后它尝试访问数据库。
SelectList 类的定义如下
public static class SelectLists
{
private static readonly ReferenceDataManager _dataManager = new ReferenceDataManager();
public static SelectList ContactClassifications(bool includeDeleted)
{
var data = _dataManager.GetContactClassifications();
}
}
它是它在 SelectList 中调用 GetContactClassifications 的那一行,感觉就像我应该能够模拟(如果调用它的方法因为它是静态的而不能被模拟)。这个确实实现了一个接口。
即使有某种方式可以模拟控制器中的私有方法(InitialiseContactVM),它也适合我。
有没有办法实现这些目标?