Mocking in C# Unit Tests – How To Test Data Access Code and More


Unit tests are great, but how do you test your data access? You sure don’t want to actually delete records when you are testing the delete method, yet you definitely want to be sure the method is configured properly. This is the type of problem that stops a lot of developers from creating unit tests. In this video, I am going to show you how to overcome these obstacles in order to write tests that handle working with external dependencies like databases.

Full courses:
Source Code:
Newsletter signup:

Tuhafeni Angula (Patreon Subscriber)



  1. @IAmTimCorey — I have a Generic-based data handler interface and associated services which I am trying to mock calls for. However, anytime I run a test, I get a NULL value from any calls to the Generic data handler. If I run the code in Production, the calls work, so I do not believe it is an issue with the way I have my services written. Any ideas what causes this kind of issue with Moq? NOTE => I am using the following NuGet Packages, in case they are the issue:

    AutoFac / AutoFac.Extras.Moq = 4.1.0 / 4.2.0
    XUnit 2.4.1
    Moq 4.13.1

    My thought is it might be an issue with AutoFac and Moq, as I already had to go back multiple versions to get Moq/AutoFac to even play well together, as it was previously failing on `var mock = AutoMock.GetLoose()`

    This seems simliar to what another user below in the comments is seeing, where your code's `cls.LoadPeople()` call is returning null for them, but not others.

    Thanks for the videos, they are most helpful when trying to learn new concepts (I am an older programmer, and mocking is not something we did in most other jobs I have held).

  2. Hi Tim,

    If you are bypassing the code of SQLLiteDataAccess class than why do we need the moq library for mocking.
    We can simply have two classes implementing ISQLDataAccess where one would return the actual data from DB and the other mock class will return the mock data.
    So we can create our app context at the starting of our app where all the interfaces would have the actual data access classes and from the testing project the context interfaces will have the mock classes

    Here using moq requires lot of code to be written as well as adding a library in your project
    Correct me if I'm wrong

  3. Hey Tim, great content as always. I was hoping to find a full unit test course on your site! I'd be a day-1 customer if you manage to put one together.

    In any case, I was hoping you might be able to help with some simple guidance if you don't mind.

    I understand mocking within the context of unit tests, but I'm wanting to mock service calls for my ViewModels that ultimately the UI binds to. Basically, I have a ViewModel that makes a service call, which hits a database and (for example) returns a list of people, in my view I have a DataGrid that binds to the results in the ViewModel. No problem. What I want to do is instead of hitting the actual database I'd like to return mocked objects.

    I have cobbled something together manually that handles this, but can you shine some light on best practices with this type of scenario? Basically what I'm doing now is I have a dummy service (both the dummy and actual service implement the same interface) and the dummy service (manually) mocks up service calls and results. I'm using dependency injection to determine which service I'm actually going to use.

    Does this sound like a decent approach? Any guidance is greatly appreciated!

  4. You think it's OK for your PersonProcessor class to create SQL query strings? That should be in your SqliteDataAccess class, which then does need to be tested, because the syntax of those query strings depends on what database engine you are using. If you wanted to support Sqlite, MySQL, Sql Server, Postgres, they don't all stictly follow standard SQL for everything. A lot of them have their own way of doing things, which is why SqliteDataAccess should create query strings for Sqlite, MySQLDataAccess should create query strings for MySQL, SqlServerDataAccess should create query strings for SqlServer, etc. And then those classes will have more code that you wrote that you do need to test.

  5. I haven't gone through the whole video yet, but you have many assertions per tests. I always thought you should write one assert statement per test?

  6. Hi Tim,
    I am quite new to unit testing, I have question for you how to you mock the below. Problem I am having is with mocking commandType.
    Many Thanks
    public void SaveData<T>(T counselEntity, string sql)


    using (IDbConnection cnn = new SqlConnection(GetConnectionString()))


    cnn.Execute(sql, new { counselEntity },commandType: CommandType.StoredProcedure);



  7. Hi Tim,
    Thanks a lot for such a wonderful video. I appreciate your advices and sharing with us how you work (for example how far do you go with test coverage). Is there any tool/platform that you would recommend for analysing test coverage, code smells, etc (i.e. sonarqube)?

  8. Hi Tim,
    I have a question if you got time for it:

    I am trying to mock a SshClient part of Ssh.Net library which I don't have control over. The part giving me problems is that this SshClient does not implement any interface so I will have direct dependency on it. What is the best way to handle this issue?

  9. Damn you Tim You videos are amazing and so addictive , it's 4 AM here and i have work tomorrow. Thanks a lot for sharing you knowledge.

  10. Tim, your videos are good, but there's one thing that is really bad about them.
    Sometimes you switch to another topic, different from the actual.
    See, this is a video about Mocking in Unit tests. I was hoping that i would watch 18 minutes and would understand some basics of what that is.
    However, all I've gotten from those first 18 minutes is:
    1) there's a cool feature in vs enterprise
    2) dependency inversion
    3) dependency injection
    4) why some classes are not injected.
    Ok, to be honest, there were some sentences related to mocking itself. But mostly you were talking about completely different things, and when you realize that you can't go deeper (when talking about another topic) you say "But that's ok, don't worry, let's skip that" or something like that.
    I understand why you do this: you don't want a newbie to get confused from DI and features in VS. But holy hell, why would you go too deep when talking about some other topic? Please, don't do this. I've caught myself several times doing some other work while having your video open, it is because it was not really interesting to listen to something like "that's an int, a type from BCL. You don't need to worry how it's implemented. It's all done for you. It just represents a numeric value. Please, don't worry! That's ok.". Sorry, if you find, let's call it, "mirroring" your speech, offensive, I didn't mean to do that (that's ok, don't worry! :D).
    Your 1h video actually could've been shortened up to 20-30 mins if you were just focusing on mocking (ok, you can say "that is injected via Dependency Injection. If you don't know what it is, don't focus on that", but don't try explain what DI is, it will take a lot of time, and also that would make some people who already know what DI is less focused on your video)

  11. Hi Tim – It is well explained video – quite complex, but if I have downloaded the code – that helped:-) But I have a problem about 29:50: My code is (in the load methode)
    .Setup(x=>x.søg<AspNetUsers>("select Email, Fornavn from AspNetUsers where Email = ''")).Returns(GetSamplePeople());
    VS do not accept the Returns as a class – It thinks it should be a method in my Interface – But I don't think so. I have tried to look for references in NuGet – but that should be ok. I am stucked – stuped mistake – plleeez help 🙂

  12. Tim, this was a good video.  I was a bit hesitant about mock frameworks as I am a firm believer in writing all code when it comes to unit test.  That's the way I was taught in the 90's.  I watched your video several times and then it clicked it my thought process on how you used moq framework and more importantly why.  I had to think back on how I  wrote all the extra code to test to realize how this can cut down on writing so much of it before being able to find bugs.  Thanks for a great video, I do appreciate this and look forward to watching more.

  13. Way too many tangents. I suggest you stick to the topic instead of going down all of the rabbit holes of IDE configuration, plug-ins, etc.

  14. I could not get the LoadPeople_ValidCall() to work. cls returns null. The SavePeople one worked….I used your starter code and copied what you did exactly. Frustrating… Great video by the way.

  15. I've been searching for a while a good content for tests in Microsoft environment and now I found a good explanation. Finally I understand the reason and how to test void and CRUD methods.

  16. Having watched your video on Unit tests yesterday; I started this video thinking how I missed the suspense of having to actually click run tests to get a green (or red) check mark. But man, the convenience enterprise provides is great! Will definitely have to look into those third party options for auto testing.
    Great video Tim, I know I'll be returning to watch again in the near future =]

  17. One useful thing is missing from the SavePeople_ValidCall() demo: comparing the PersonModel passed into ISqliteDataAccess.SaveData() to the PersonModel passed into SavePerson(), to ensure SavePerson() isn't modifying (or alternatively is correctly modifying) the data before persisting it.

  18. I come here to learn how to mock access data layer, but instead I end up fordwarding the 95% percent of the video because you were explaining a lot of .NET stuff that has nothing to do with mocking (like "using" keyword, nugget dependencies, tupplets, visual studio enterprise, just to mention someones…)

  19. I always feel like I'm close to understanding the purpose of mocking. But I never really get there by watching videos. The examples I see is basically just tests to see if hard coded values matches other hardcoded values. It feels like we are not really getting a unit-test but more a new kind of interface thats ment for parameters and return values. Since the Mocks I have seen so far is saying "this is what this function needs to do. Every time. It needs to have this parameter or maybe this return value". But if its that static why dont we just use normal Asserts for this without Mocks since the mocked values are hardcoded in the end. Maybe its just because beginner examples are not complex enough. But it would be interesting to see a example of where a mock-test actually secures code.

    Getting a failed test every time a method returns something else or uses a different param then a specific case seams kind of.. troublesome.

  20. Great video Tim thanks. Never really done any unit testing as the firms I've work at don't seem to do them, so never really got into them. AutoFac… Looks like I missed a video – DI With AutoFac – YT seems to think I've watched it. I'll have to go and watch that now as I had no idea what AutoFac is.

  21. Hey Tim, just a friendly suggestion on how to name your Unit Test methods.

    I’ve learned that using this naming pattern helps with alleviating any confusion on what the purpose of each test method is:


    Hopefully that helps!

  22. Uuuh, dumb question: how have you written those test classes?

    Also 13:55 what if you want to actually test the DB interractions? 😛

    34:44 I don't get it, we are mocking the data returrn by the sql method, why changing the sql string parameter fails the test?

    Seems like a neat framework though. 😛

  23. Hello Sir , thank you for all tutorials. Also , if you can make intermediate Web api project from scratch, it would be perfect for us. ( I finished your Web api tutorial and it was awesome. That's why I wanted one more full project 🙂 )

    Thank you again for your all videos Sir.


Please enter your comment!
Please enter your name here