Moq,SetupGet,嘲弄一个属性

我试图嘲笑一个名为UserInputEntity的类,它包含一个名为ColumnNames的属性:(它包含其他属性,我已经简化了它的问题)

 namespace CsvImporter.Entity { public interface IUserInputEntity { List<String> ColumnNames { get; set; } } public class UserInputEntity : IUserInputEntity { public UserInputEntity(List<String> columnNameInputs) { ColumnNames = columnNameInputs; } public List<String> ColumnNames { get; set; } } } 

我有一个主持人class:

 namespace CsvImporter.UserInterface { public interface IMainPresenterHelper { //... } public class MainPresenterHelper:IMainPresenterHelper { //.... } public class MainPresenter { UserInputEntity inputs; IFileDialog _dialog; IMainForm _view; IMainPresenterHelper _helper; public MainPresenter(IMainForm view, IFileDialog dialog, IMainPresenterHelper helper) { _view = view; _dialog = dialog; _helper = helper; view.ComposeCollectionOfControls += ComposeCollectionOfControls; view.SelectCsvFilePath += SelectCsvFilePath; view.SelectErrorLogFilePath += SelectErrorLogFilePath; view.DataVerification += DataVerification; } public bool testMethod(IUserInputEntity input) { if (inputs.ColumnNames[0] == "testing") { return true; } else { return false; } } } } 

我已经尝试了下面的testing,我嘲笑实体,尝试获取ColumnNames属性返回一个初始化的List<string>()但它不工作:

  [Test] public void TestMethod_ReturnsTrue() { Mock<IMainForm> view = new Mock<IMainForm>(); Mock<IFileDialog> dialog = new Mock<IFileDialog>(); Mock<IMainPresenterHelper> helper = new Mock<IMainPresenterHelper>(); MainPresenter presenter = new MainPresenter(view.Object, dialog.Object, helper.Object); List<String> temp = new List<string>(); temp.Add("testing"); Mock<IUserInputEntity> input = new Mock<IUserInputEntity>(); //Errors occur on the below line. input.SetupGet(x => x.ColumnNames).Returns(temp[0]); bool testing = presenter.testMethod(input.Object); Assert.AreEqual(testing, true); } 

我得到的错误状态,有一些无效的参数+参数1不能从string转换为

 System.Func<System.Collection.Generic.List<string>> 

任何帮助,将不胜感激。

ColumnNames是一个List<String>types的属性,所以当你设置你需要在Returns调用中传递一个List<String>作为参数(或者返回List<String>的func)

但是,这条线你只是想返回一个string

 input.SetupGet(x => x.ColumnNames).Returns(temp[0]); 

这是造成例外。

将其更改为返回整个列表:

 input.SetupGet(x => x.ColumnNames).Returns(temp);