My code looks as below:
public class FileFormatLookup : Dictionary<string,Func<string>>
{
private Workbook workbook;
private MemoryStream memoryStream;
public FileFormatLookup(Workbook workbook, MemoryStream memoryStream)
{
this.workbook = workbook;
this.memoryStream = memoryStream;
Add();
}
private void Add()
{
base.Add("xls", () =>
{
workbook.Save(memoryStream, SaveFormat.Excel97To2003);
return "ms-excel";
});
}
}
And I am trying to write the test as below:
class FileFormatLookupTest
{
FileFormatLookup fileFormatLookup;
private Workbook workbook;
private MemoryStream memoryStream;
[SetUp]
public void SetUp()
{
fileFormatLookup = new FileFormatLookup(workbook, memoryStream);
workbook = MockRepository.GenerateMock<Workbook>();
memoryStream = MockRepository.GenerateMock<MemoryStream>();
}
[TearDown]
public void TearDown()
{
workbook.VerifyAllExpectations();
}
[Test]
public void ShouldHaveXlsKey()
{
var xlsResult = fileFormatLookup["xls"].Invoke();
workbook.AssertWasCalled(x=>x.Save(memoryStream,SaveFormat.Excel97To2003));
}
}
Is this the correct way to test a functor inside dictionary?
It throws this error :
System.InvalidOperationException : No expectations were setup to be verified, ensure that the method call in the action is a virtual (C#) / overridable (VB.Net) method call
How do I test a dictionary which returns a function? Is it possible?
I can assert the string value which is returned but not the method calls.
You are not passing your mocks to the class being tested.
Change setup to
From the error message, it looks like to need to set up expectations, i.e. which calls on the mock objects you are expecting. In this case
workbook.Save(...).To do this,
workbook.Save(...)must be either virtual or on an interface.Edit: after further information provided as a comment.
If the
workbook.Save(...)is not virtual and not within your code, you must go a slightly longer route to be able to test the object.Create your own
IWorkbookinterface which implements theSave()method, then aWorkbookWrapperclass which contains an instance of the 3rd partyWorkbookclass and implementsIWorkbookby forwarding calls to the wrapped class.Then change your code to take an
IWorkbookinstead:You could then use the same technique for other classes, e.g. the
MemoryStream.