Moq, SetupGet, Mocking a property
I'm trying to mock a class, called UserInputEntity
, which contains a property called ColumnNames
: (it does contain other properties, I've just simplified it for the question)
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; }
}
}
I have a presenter 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;
}
}
}
}
I've tried the following test, where I mock the entity, try to get ColumnNames
property to return a initialized List<string>()
but it's not working:
[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);
}
The errors I get state that there are some invalid arguments + Argument 1 cannot be converted from string to
System.Func<System.Collection.Generic.List<string>>
Any help would be appreciated.
Solution 1:
ColumnNames
is a property of type List<String>
so when you are setting up you need to pass a List<String>
in the Returns
call as an argument (or a func which return a List<String>
)
But with this line you are trying to return just a string
input.SetupGet(x => x.ColumnNames).Returns(temp[0]);
which is causing the exception.
Change it to return whole list:
input.SetupGet(x => x.ColumnNames).Returns(temp);
Solution 2:
Mocking read-only properties means properties with getter method only.
Note that you should declare it as virtual
, otherwise System.NotSupportedException
will be thrown.
If you're using an interface, that does not apply to you. It works instantly because the mock framework will implement the interface on the fly for you.