问题
Possible Duplicate:
What would be an alternate to [SetUp] and [TearDown] in MSTest?
I'm learning how to use Unit Testing and automated testing in general and have a few questions I can't figure out/find the answer to
I currently test by having multiple [TestMethod]s that call various methods and have asserts in them. Right now the TestMethod's all have duplicate code to hit a DB and set themself up for the rest of the test. An example is:
public void TestDBReturnsFooInFormatXyz() {
var foo = HitDBAndReturnStuff();
Assert.IsTrue( // foo format is xyz );
}
public void TestDBFooContainsAbc() {
var foo = HitDBAndReturnStuff();
Assert.IsTrue( // foo contains abc );
}
So some questions: Is it a best practice to make private fields in a test class and have the constructor set them?
Should I do it in each TestMethod because testing speed doesn't matter that much?
What [Test???] do I put on top of the constructor to make sure it gets called when running tests?
I've looked at MSDN and the book "Programming Microsoft Visual C# 2008: The Language" and I can't find any good information on unit testing. If there is a resource I should have read which answers these questions just let me know.
Thanks!
回答1:
Duplicated code is always a bad practice, so you should refactor your code to initialize the foo object in the TestInitialize Method, which executes once before each test run, and then perform specific operations in each test case:
private FooType foo;
[TestInitialize()]
public void TestInitialize()
{
foo = CreateFooObject();
}
[TestMethod()]
public void TestToAssertThatAbcStuffGetsDone()
{
foo.DoAbcStuff();
Assert.IsTrue(foo.DidAbc());
}
[TestMethod()]
public void TestToAssertThatXyzStuffGetsDone()
{
foo.DoXyzStuff();
Assert.IsTrue(foo.DidXyz());
}
If your foo object needs to be disposed after each test method run, you should also implement a TestCleanup Method.
However, using a database in your unit tests is not considered a best practice because you don't want external dependencies affecting your tests results. Instead, you should use a database mock that acts like a database but isolates your unit tests from the real database dependency.
Several database related problems could break your tests, such as connection failures, timeouts, data changes and occasional database upgrades. This SO question discusses strategies for handling the database dependency issue.
来源:https://stackoverflow.com/questions/13943078/c-sharp-unit-test-with-common-code-repeated