How do I start unit testing?

后端 未结 8 1008
盖世英雄少女心
盖世英雄少女心 2020-12-15 12:48

I know that unit testing is desirable, and I am interested in doing unit testing. The only problem is I have no idea how, or even where to start really. So my question is:

相关标签:
8条回答
  • 2020-12-15 13:42

    If you really want to understand unit testing (and get hooked), try it out, it should only take a few hours!

    First, I recommend downloading a unit testing framework, such as NUnit (if you want to start with .NET / C#).

    Most of these frameworks have online documentation that provides a brief introduction, like the NUnit Quick Start. Read that documentation, then choose a fairly simple, self-contained class for which you are responsible. If you can, try to choose a class that:

    • Has few or no dependencies on other classes - at least not on complex classes.
    • Has some behavior: a simple container with a bunch of properties won't really show you much about unit testing.

    Try writing some tests to get good coverage on that class, then compile and run the tests.

    Unit testing is simple to learn and hard to master (apologies for the cliché, but it is appropriate here), so once you've done this, start reading around: for example, guerda has provided several excellent links in another answer to this question.

    0 讨论(0)
  • 2020-12-15 13:42

    Find-a-bug-write-a-test

    The next time you find a bug in your code base, before fixing it, write a test. The test should fail. Then, fix the bug. The test should pass.

    If the test doesn't pass, there's either a bug in your test, or a bug in your fix.

    A person will never find that bug in your code again. The unit tests will find it (and faster than a person can).

    This is definitely a small start, but it gets you into testing. Once you've got the hang of it, you'll probably start writing more tests, and eventually get a knack for how code will fail and which tests you need (for example: a test for every business rule).

    Later in your progression you setup a continuous integration server, which makes sure your codebase is always solid.

    0 讨论(0)
提交回复
热议问题