I'm trying to mock an Excel spreadsheet using NSubstitute or other mocking framework and MSTest (Visual Studio 2010). I'm not sure if there's a better way than this--and this doesn't quite work for testing:
Here's an example (this is all prototype code right now, and not very clean):
int[] lowerBounds = { 1, 1 };
int[] lengths = { 2, 2 };
//Initialize a 1-based array like Excel does:
object[,] values = (object[,])Array.CreateInstance(typeof(object), lengths, lowerBounds);
values[1,1] = "hello";
values[2,1] = "world";
//Mock the UsedRange.Value2 property
sheet.UsedRange.Value2.Returns(values);
//Test:
GetSetting(sheet, "hello").Should().Be("world"); //FluentAssertions
So far, so good: this passes if the GetSetting method is in the same project as my test. However when GetSetting is in my VSTO Excel-Addin project, it fails with the following error on the first line of the GetSetting function:
System.MissingMethodException: Error: Missing method 'instance object [MyExcel.AddIn] Microsoft.Office.Interop.Excel.Range::get_Value2()' from class 'Castle.Proxies.RangeProxy'.
For reference, the GetSetting grabs a value from columnA in the sheet, and returns the value in columnB.
public static string GetSetting(Excel.Worksheet sheet, string settingName) {
object[,] value = sheet.UsedRange.Value2 as object[,];
for (int row = 1; row <= value.GetLength(1); row++) {
if (value[1, row].ToString() == settingName)
return value[2, row].ToString();
}
return "";
}
The final interesting piece is if I redefine the signature of my method as follows:
public static string GetSetting(dynamic sheet, string settingName)
it works in the VSTO project.
So what is going on, and what's the best way to do something like this?
Thanks!