Using Moq and TDD, where to start?

后端 未结 4 2189
灰色年华
灰色年华 2021-02-14 10:45

I have a server application and I was wondering where I should start if I want to start implementing TDD and using Moq.

What good books I could read on the subject, wh

4条回答
  •  后悔当初
    2021-02-14 11:07

    I recommend two books: Test Driven Development by Example, by Kent Beck. It's an excellent book on TDD, which I particularly enjoy because he walks through an example, which is very useful in getting a sense for the rhythm and thought process. On the other hand, it's a bit light on mocking. For that I would read The Art of Unit Testing, by Roy Osherove. As the title suggests, it's not focused on TDD specifically, but rather on how to write good unit tests; he has a good coverage on mocks and stubs.

    Regarding what you should mock, the idea of mocking is to allow you to isolate the class/function you are testing from the rest of the environment, so that you can test its behavior against a fake environment you control. In that frame, you should not be mocking the class, but rather things it depends upon.

    A trivial example: if you had a class using a Logger, testing that the class "writes" to the logger would be very painful, and could involve things like checking whether the logger has written in a text file. This is not a good idea on lots of levels - starting with the fact that your class doesn't care about how the logger does its job specifically. In that case you would replace the Logger instance in your class with a Fake, mocked Logger, and you can then verify that your class is calling the Logger at appropriate times, without worrying about what the logger does, exactly.

    Regarding server initialization: a unit test is typically in memory, with no dependencies to the environment, so if you are doing TDD, you should probably not have to do that. In general, too much (any?) initialization code in a unit test is a bad sign.

    This suggests that you are looking more for acceptance tests / BDD style tests. I recomment this recent article in MSDN Magazine on Behavior-Driven Development with SpecFlow and WatiN; it explains how you can develop in a test-first manner by developing together high-level tests which verify that the application is doing what the user wants (acceptance tests, where you would run your actual server and app), and that it's doing it by having small pieces of code that do what the developer intends (unit tests).

    Hope this helps, and happy testing!

提交回复
热议问题