问题
I'm trying to get started with Moq and having trouble finding any good resources to do what I need.
I have a Data Interface class that has a Get method which returns a Dataset via Stored Procedure. This is the way the code was written and I can't change it at the moment so it has to be done this way.
I want to test this class by Mocking the Dataset and returning data so I don't have to actually make a database call.
Is anyone doing this and if so where is a good place to get started doing it?
回答1:
You don't need a database connection to fill in a DataSet. You can mock it like this:
IDataInterface di = new Mock<IDataInterface>();
DataSet mockDataSet = CreateMockDataSet();
di.Expect(x => x.Get()).Returns(mockDataSet);
something.UseDataInterface(di.Object);
Filling in a mock DataSet is quite painful, though. If I'm doing this, I generally put a facade interface in front of the returned DataSet, which is easier to mock. Or I change the code to use a DataTable, which is easier to fill in.
Alternatively, use an embedded database, such as SQLite or SQL Server CE, for your unit tests.
回答2:
I also faced above problem and came up with this solution. I am sharing it because I was not able to find anything on google for this:
[TestCategory("GetDataSet")]
[TestMethod]
public void GetDataSet_ValidCall_ShouldPass()
{
// Arrange
var dataSet = Builder<DataSet>.CreateNew().Build();
DataTable table1 = new DataTable();
table1.Columns.Add("Id", typeof(int));
table1.Columns.Add("Name", typeof(string));
table1.Rows.Add("1", "Name1");
DataTable table2 = new DataTable();
table2.Columns.Add("More", typeof(bool));
table2.Rows.Add(false);
dataSet.Tables.Add(table1);
dataSet.Tables.Add(table2);
objectWhichHaveProcMethod.Setup(elem => elem.ExecuteProcAndGetDataSet("YourSprocName", It.IsAny<SqlParameter>(), It.IsAny<SqlParameter>())).Returns(dataSet);
// Act
var response = dataInterfaceClass.Get();
// Assert
Assert.AreNotEqual(response, null);
}
来源:https://stackoverflow.com/questions/579075/mocking-datasets-with-moq