Category Archives: NUnit

NHibernate Session Manager needs HttpContext for NUnit testing

In a codebase I work in, NHibernate needs an HttpContext to get its current session – like this:


public static ISession GetCurrentSession()
{
var context = HttpContext.Current;
var currentSession = context.Items[CurrentSessionKey] as ISession;
...

To get my hands on a session for a NUnit test – I put this in the setup:


HttpContext.Current = new HttpContext(
new HttpRequest(null, "http://tempuri.org", null),
new HttpResponse(null));

 

Also, I wipe the context in the teardown:

<code>

[TearDown]
public void TearDown()
{
HttpContext.Current = null;

}

</code>

Credit for this goes to :

http://caioproiete.net/en/fake-mock-httpcontext-without-any-special-mocking-framework/

Rolling rolling rolling – rolling back your data back in integration tests

A couple years ago, I had just started refactoring a legacy codebase by adding integration tests and was manually rolling back the database changes with several lines of handwritten sql deletes… (sorry). At Iowa Code Camp, I went to a Lee Brandt demo and looking at Lee’s demo code, I saw him using a transaction for the rollbacks and I hung my head in shame.

Try it like this:

using NUnit.Framework;
using System.Transactions;
namespace ProjectName.Tests.Integration
{
 [TestFixture]
 public class TestClass
 {
 private TransactionScope _transactionScope;
 [SetUp]
 public void SetUp()
 {
 _transactionScope = new TransactionScope(TransactionScopeOption.RequiresNew);
 }
 //...Test some stuff, insert records, update records, etc...
 [TearDown]
 public void TearDown()
 {
 _transactionScope.Dispose();
 }
 }
}

Happy Testing,

Jim