Linq-SQL Query Logic for Unit Testing

I am trying to write some unit tests for my code. In the project, we use Linq-SQL objects created from DBML. I am trying to figure out how I need to test the following logic.

Say, for example, I need to get the number of records from a table using LINQ.

var objectCount = (from x in DB.MyRecords
                  where x.DateAdded.Date == DateTime.Now.Date
                  select x).Count(); //For example this will return 4

if(objectCount > 3)
{
   //Do some logic here
}
else
{
   //Do some logic here
}

Now I understand that unit test is not really unit test if you are accessing a database.
My request is also more in demand than the fact that the data structure contains Forign keys that must be supported.
Now the next problem is that because we use the LINQ-SQL object, we don’t use interfaces, so we can’t use the fake framework (or can we ????) I would like to know that this the process must have a unit test.

+3
source share
2 answers

For testing, you need intermediate classes between your DBML and business logic code. Take a look at the repository template for more information on this.

, , , , 10 . , , , , ( ). :

public interface IRepository
{
    int CountProduct();
}

// your implementation of repository against real database
public class DBLinqToSQLRepository : IRepository
{
    // some constructor here

    public int CountProduct()
    {
        // your code here to return the actual number of product from db.
    }
}

// your implementation of fake repository that will provide fake data for testing
public class FakeRepository : IRepository
{
    private List<Product> products = new List<Product>();

    // some initialization here

    public int CountProduct()
    {
        return products.Count;
    }
}

FakeRepositor -.

+2

Repository, , .

public int GetNumberOfItemsAddedToday()
{
    return from x in DB.MyRecords
           where x.DateAdded.Date == DateTime.Now.Date
           select x).Count();
}

, ( - Moq, RhinoMocks). , LINQ To SQL, SO , .

unit test

, , integration tests.

+1

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


All Articles