Address: http://blog2.matthidinger.com/archive/2009/09/08/automatically-roll-back-your-linq-to-sql-integration-tests.aspx
Today, I started to test the data in MVC. At the beginning, I tried to search for some simple methods to test the data in LINQ, because rollback is used in most cases, but I finally chose to write it myself. It may be helpful for some people to record it. This base class is written in the Microsoft environment, but the nunit and xunit modes can be used after simple modifications.
The Code is as follows:
First, we simply inherit this base class, change the test class through the internal context attribute, and then simulate automatic rollback. This is true for each test.
/// <Summary>
/// The base class will allow LINQ to SQL integration testing with automatic rollbacks after each test
/// </Summary>
/// <Typeparam name = "tcontext"> the type of data context to use </typeparam>
Public abstract class rolledbackdatacontexttests <tcontext> where tcontext: datacontext
{
Private tcontext _ context;
Private dbtransaction _ transaction;
[Testinitialize]
Public void initdatacontext ()
{
If (string. isnullorempty (connectionstring ))
{
_ Context = (tcontext) activator. createinstance (typeof (tcontext ));
}
Else
{
_ Context = (tcontext) activator. createinstance (typeof (tcontext), connectionstring );
}
_ Context. Connection. open ();
_ Transaction = _ context. Connection. begintransaction ();
_ Context. Transaction = _ transaction;
}
/// <Summary>
/// Provides access to the internal data context. Any changes made will be automatically rolled back
/// </Summary>
Protected tcontext Context
{
Get
{
If (_ context = NULL)
Initdatacontext ();
Return _ context;
}
}
/// <Summary>
/// Optionally specify the connection string to use
/// </Summary>
Protected virtual string connectionstring
{
Get
{
Return NULL;
}
}
[Testcleanup]
Public void testcleanup ()
{
_ Transaction. rollback ();
_ Context. Dispose ();
_ Context = NULL;
}
}
[Testclass]
Public class sqlrepositorytests: rolledbackdatacontexttests <northwinddatacontext>
{
// Insert as your products as required and then exercise your database integration test methods
Public void insertproducttocontext ()
{
Product P = new product {productname = "temporary product "};
Context. Products. insertonsubmit (P );
Context. submitchanges ();
// After each test ends, the transaction will be rolled back, and the new product will not be in the database
}
[Testmethod]
Public void test1 ()
{
// Test logic here
}
}