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

IAmTimCorey · 309K views · 2018 · 1:02:34

Open on YouTube

Testing, debugging & developer toolsSoftware architecture & designtutorial

Why Stack Overflow recommends it

Stack Overflow users link it as a practical walkthrough of mocking with Moq in C# unit tests, and for the Visual Studio test tooling visible in its demo.

Recommended by 0 people across 0 different months, 2019 to 2023.

What it is

A one-hour tutorial by Tim Corey on unit testing C# code that depends on external resources such as databases. He walks through a demo app, explains mocking, and writes tests using AutoMock (Moq with Autofac), covering void methods, comparing objects, and checking SQL calls.

What people said

Cites Stevens Qiu · 2019-08 · Stack Overflow · on “How can I return an object (ie. List<string>) from an object mocked with NSubstitute?”

I am using NSubstitute to mock one of my classes/interfaces. One of the functions implemented by my class should return an object of type List. But when I try to use _mockedObject.MyFunction().Returns(myList), it gives me an error saying I cannot convert between my List and an object of type Func. I figured I could pass my list as a string using some ToString() function and convert it back? But that doesn't seem particularly clean as I'm expecting a list to come back from my function. I saw from a video on Unit Testing with Dependency Injection that you can return objects from mocked objects with Moq ( [this video] ). I am considering switching to that if I can't manage to return an object with N

Cites Incorporeal Logic · 2020-02 · Stack Overflow · on “Moq Test - Mocked Service Call Always Returns Null”

I am new to Moq and Mocks/Unit Testing in general. After watching a video on Mocking which uses Moq [this video] , I thought I had enough understanding to start setting up a few simple tests for a project I am working on. However, no amount of fiddling with the code helps my first test pass. Here is the code I have: Interface Being Tested public interface IDataInterface { Task<IList<T>> GetData<T>(string url); // Other stuff } Implementation of Interface Method GetData<T> public async Task<IList<T>> GetData<T>(string url) { try { var json = await client.GetAsync(url).Result.Content.ReadAsStringAsync(); var data = (JObject)JsonConvert.DeserializeObject(json); JArray arr = (JArray)data["resource"];

Cites SIT_account · 2023-09 · Stack Overflow · on “How to view live code coverage in Visual Studio?”

I have Visual Studio Enterprise. At the linked timestamp, this guy [this video] has green little checkmarks on the left side of his window that seem to show code coverage in real time. How do I turn this on? I tried searching all over, but I don't know what this setting is called.