user1181942
user1181942

Reputation: 1607

Nunit --Data insert test issue

I am new to Nunit testing. I am trying to write test method for a method which inserts data in Database.

My code is like:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NUnit.Framework;
using MBT.Entities;


[TestFixture]
public class TagStoreTest
{
    private Tag testTag;

    public TagStoreTest()
    {
      this.testTag = new Tag();
    }

[Test]
public void InsertTagTest()
{
    TagStore tagSt = new TagStore();
    bool isInserted = tagSt.InsertTag(this.testTag);

    Assert.IsTrue(isInserted);
}


[SetUp]
public void Setup()
{
    this.testTag.TagName = "testtagthroughNunit";
}

     [TearDown]
     public void TearDown()
     {

     }

 }

And actual TagStore code is like

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MBT.Datastore;
using System.Data;

using MBT.Entities;


  public class TagStore
 {
   private string _connectionString = string.Empty;

   public TagStore()
   {
    this._connectionString = SqlHelper.GetConnectionString();
    }


    public bool InsertTag(Tag tag)
   {
     bool isInserted = false;

     using (DatabaseHelper helper = Utility.DbHelper)
     {
        int tagsAdded = helper
            .AddInputParameter("@Tag", tag.TagName)
            .AddInputParameter("@ParentTagId", tag.ParentTagId)
            .ExecuteNonQuery("Proc_InsertTags", CommandType.StoredProcedure);

        if (tagsAdded > 0)
        {
            isInserted = true;
        }
    }
    return isInserted;
 }
}

When i run test i get error: TagStoreTest.InsertTagTest: System.NullReferenceException : Object reference not set to an instance of an object.

And code line TagStore tagSt = new TagStore(); is highlighted in red.

I dont know whats going wrong because my project builds successfully but i get error when i run test.

Upvotes: 1

Views: 765

Answers (1)

activebiz
activebiz

Reputation: 6230

I see your TagStore constructor is setting connectionString member. Try to debug what is returned by

SqlHelper.GetConnectionString();

Your SqlHelper could be playing tricks.

I also suggest try using some sort of mocking technique to isolate tests. For e.g. you can mock the SqlHelper object which always returns a desired connectionstring. There are plenty of framework out there for e.g. Moq.

Upvotes: 1

Related Questions