How would I do TDD with a COM OLE object

2020-04-12 09:48发布

问题:

I have an OLE COM object that trying to write a wrapper for, I have decided to start to use TDD to write the code for it as I believe that it will give me a better sense of direction with what I'm try to write. The COM object has a interface like this:

Interface Mapinfo
    Sub [Do](ByVal cmd As String)
    Function Eval(ByVal cmd As String) As String
End Interface

The [Do] command would take somthing like the following

Mapinfo.Do("OpenTable("""C:\Temp\MyTable.TAB""")")

Now I am trying to write a wrapper so there is a function like this:

Mapinfo.OpenTable("C:\Temp\MyTable.TAB")

Now my main problem that I'm having, is that every time I want to write a new test and some code I have to create an instance of the OLE object,wait for the application to start(30 secs+), test my little function,close and dispose OLE object, change code and run it all again.

My question is: Is there a better way to do all of this with out having to start the OLE app every time? I have heard about mock objects but haven't really looked into it much, would they help me here? If so how?

EDIT: I have now realized that I will have to make a mock object for Mapinfo, my question is how do I make a make a mock object that can take different formated strings? How will this help me verify that the code in my wrapper is correct?

回答1:

Yes, mock objects would help. Essentially, you create a fake Mapinfo object by mocking the Mapinfo interface (you should rename that IMapInfo, btw).

You then instruct that mock what calls to expect, and what results to return (if appropriate). You can also create tests where the mock throws exceptions or does other things that are hard to invoke using the real object.

The two big (and free) .NET mocking frameworks are MoQ and Rhino Mocks. Rhino is more mature and has more ways of configuring mocks. MoQ is the newcomer and has a smaller featureset and less ways of setting expectations than Rhino.

Personally, I think MoQ is better for the newcomer to mocking. Its relatively easy to understand, all the documentation out there is relevant to the current release (search for Rhino tutorials and you get junk from years ago that doesn't apply anymore), and it performs well.