Testing Linqto SQL Classes

How do I unit test my code with LTS Datacontext. I am getting an error while testing, I have a lot of Datacontexts and manually adding the Connection string is a pain, any suggestions.

+1


a source to share


1 answer


Ok how I do it:

My data layer has an interface like:

public class MyDataLayer : iMyDataLayer
{
  public string GetMyData(parameters)
  {
    return myQueryValue;
  }

}

public interface iMyDataLayer
{
  public string GetMyData(parameters);
}

      

Now, in my constructor for my main codebase (business logic), I will have a parameter to pass in the frontend for the data layer:

private iMyDataLayer DataLayer;

public class MyBusinessLogic(iMyDataLayer dataLayer)
{
   DataLayer = dayaLayer
}

public string GetMyData(parameters)
{
  return DataLayer.GetMyData(parameters)
}

      



With this, I can now create a "fake" data service in my TDD project:

public class FakeDataLayer : iMyDataLayer
{
      public string GetMyData(parameters)
      {
        return "Some Default Value or Object";
      }

}

      

So now when I run my test, now I can pass my fake data layer object to my business logic, from here it will call the fake logic and return the default result.

Now given to you, you won't be working with real data here. However, if you are setting up fake objects with real valid / invalid data, you can test your business logic that way without connecting to the database.

Hope this helps. Let me know if you need to clarify anything.

+1


a source







All Articles