Rollback NUnit after testing

I am new to NUnit (and automatic testing in general). I recently did some Ruby On Rails work and noticed that in my test case, when I create objects (like a new user) and commit them during the set, they are never database bound, so I can run again and again. and don’t worry that the user already exists.

Now I'm trying to accomplish the same thing in NUnit, but I'm not quite sure how to do this. Create transaction in Setup and Teardown blocks? Thanks.

+6
source share
4 answers

Why do you need to talk to the database during unit tests? This makes your unit test a default integration test. Instead, create wrappers for all communication with the database and prepare / mock it during unit tests. Then you do not need to worry about the state of the database before and after.

Now, if you do not want this level of refactoring: the problem with transactions is that you need to open the connection. Thus, if your test method handles all communication on its own, it’s really difficult to enter a transaction that you can create during setup and roll back when disconnected.

+5
source

Maybe you can use this. This is ugly, but maybe this might work for you:

namespace SqlServerHandling { [TestFixture] public sealed class TestTransactionRollBacks { private string _connectionString = "Data Source = XXXDB; ; Initial Catalog = XXX; User Id = BLABLA; Password = BLABLA"; private SqlConnection _connection; private SqlTransaction _transaction; [SetUp] public void SetUp() { _connection = new SqlConnection(_connectionString); _transaction = _connection.BeginTransaction(); } [TearDown] public void TearDown() { _transaction.Rollback(); } [Test] public void Test() { Foo foo = new Foo(_connection); object foo.Bar(); } } internal class Foo { private readonly SqlConnection _connection; object someObject = new object(); public Foo(SqlConnection connection) { _connection = connection; } public object Bar() { //Do your Stuff return someObject; } } 
+5
source

I agree with Morten, but you can look at this very old MSDN Magazine article on this topic: Know your code: Simplify data-level testing with Enterprise Services

+3
source

I use SQLite for unit tests using NHibenate. Even if you are not using NHibernate, this should be possible. SQLite has a memory mode in which you can create a database in memory and save the data there. This is fast, works well, and you can simply throw away and recreate the circuit for each test or fixture as you see fit.

You can see t he example from the Ayende blog for an overview of how this is done. It uses NHibernate, but the concept should work with other ORMs or with direct DAL.

0
source

Source: https://habr.com/ru/post/886873/


All Articles