Ways of unit testing data access layer

前端 未结 3 541
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-28 08:26

I have be trying to look for an effective way in unit testing my data access layer in C#. I\'m primary a Java developer and have only used C# for about 6 months, in the past

相关标签:
3条回答
  • 2020-12-28 08:56

    This layer's job is to connect the code to the database. It has to encapsulate the knowledge about db connection and syntax. In usually maps the domain language to database language. I look at this part of the unit tests as integration test, and as such I test that the database schema is equivalent against real or test database. More on the subject here.

    0 讨论(0)
  • 2020-12-28 08:57

    It's unfortunate that you can't find a tool that puts your database into a known state and lets you run your CustomerRepository against the database to test the CustomerRepository. However, the answer is not to start using mocks to mock out all of the ADO calls. By doing that, you end up creating a unit test that doesn't really test any logic: it's just testing that the code is written the way you think it should be written.

    Let's say that I end up writing a SQL INSERT as my command to create the customer in the SQL database. Now let's say that we're making a change so that the customer table has different fields (that breaks our INSERT command) and that now we should be using a stored procedure to create the customer. The test with mocks would still pass, even though the implementation it's testing is now broken. Additionally, if you fixed the implementation to use stored procedures, your unit tests would now fail. What is the point of a unit test if it continues to pass when it should fail but then would fail when you fixed the system?

    See this question for some possible alternatives. It looks like the marked answer is to actually just end up using DBUnit in C# using IKVM.

    So, there might be alternative avenues to continue to explore, but mocking the ADO calls is just going to lead to brittle tests that don't really test anything important.

    0 讨论(0)
  • 2020-12-28 09:09

    To test DataAccess Layer you will need a more complex structure.

    DataAccess Layer will call references from Repository objects. Repo object will call references from Entity Framework DbSets via UnitOfWork design pattern.

    DataAccess Layer (TOP)
    |
    UnitOfWork
    |
    Repository Pattern Classes
    |
    EF Context
    |
    Actual Database

    After you set structure, then you will mock repository classes. For example, items will be inserted to DB instead will go to mock object. Later you will assert against your mock object to see item inserted or not.

    Please take a look at Implementing the Repository and Unit of Work Patterns

    0 讨论(0)
提交回复
热议问题