Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are a couple good ways to provide data to tests in .NET. One is to use features built into NUnit such as parameterized tests and theories. </p> <h1>Parameterized Tests:</h1> <p>The <a href="http://www.nunit.org/index.php?p=testCase&amp;r=2.5.8" rel="nofollow">TestCaseAttribute</a> allows you to easily supply hard-coded data to a test as in the following example from nunit.org:</p> <pre><code>[TestCase(12,3, Result=4)] [TestCase(12,2, Result=6)] [TestCase(12,4, Result=3)] public int DivideTest(int n, int d) { return( n / d ); } </code></pre> <p>The <a href="http://www.nunit.org/index.php?p=testCaseSource&amp;r=2.5.8" rel="nofollow">TestCaseDataAttribute</a> lets you get much more fancy in supplying data (such as returning data from a database).</p> <h1>Transactions for Rollback</h1> <p>Another trick often used is relying on transactions. Basically, start a Transaction before the test, and roll it back after. This can even be automated using a base class so you're tests don't deal with the transactions themselves at all. For example, you might have a base class for your test fixture like the following:</p> <pre><code>public class TestBase { private TransactionScope _transacation; [SetUp] public virtual void InitializeTest() { //NOTE: Base class TestInitialize methods are called before test Initialize methods in derived class. // Setup a DB transcation to roll everything back after the tests. if (_transacation != null) throw new Exception("old transacation still exists"); // Give a long timeout on this transacation for debugging... _transacation = new TransactionScope(TransactionScopeOption.RequiresNew, TimeSpan.FromSeconds(60)); } [TearDown] public virtual void CleanupTest() { // Roll all the changes made during the test back. _transacation.Dispose(); _transacation = null; } } </code></pre> <p>Since the TestInitialize decorated methods on the base class are called <em>before</em> TestInitialize methods in derived class, you can even add some data to the database in your parent class' TestInitialize method.</p> <p>A parent class might look like:</p> <pre><code>[TestFixture] public class MyClassTests : TestBase { [TestFixtureSetUp] public void InitializeUnit() { //Setup mocks... } [SetUp] public override void InitializeTest() { base.InitializeTest(); // Add test data to database } [Test] public void RealTest() { ... } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload