Setting up mock objects for EF dbcontext to test repository methods

Setting up mock objects for EF dbcontext to test repository methods

By : Patrick Clark
Date : November 21 2020, 03:00 PM
it should still fix some issue I am assuming that you are trying to mock WorldContextand to use it with your repo instance ,so we need to mock that first. To do that create an interface for worlddbcontext.
code :
public interface IWorldContext
        DbSet<Stop> Stops { get; set; }
        DbSet<Trip> Trips { get; set; }
 private Mock<IWorldContext> _context;
 private WorldRepository _repo;

        public void Test_AddTrips()

            var data = new List<Stop> {
                 new Stop
                    Arrival = DateTime.Now.AddDays(-15),
                    Id = 1,
                    Latittude = 0.05,
                    Longitude = 0.004,
                    Name = "Test Trip01",
                    Order = 1
                   new Stop
                    Arrival = DateTime.Now.AddDays(-20),
                    Id = 2,
                    Latittude = 0.07,
                    Longitude = 0.015,
                    Name = "Test Trip02",
                    Order = 2


            var mockSet = new Mock<DbSet<Stop>>();
            mockSet.As<IQueryable<Stop>>().Setup(m => m.Provider).Returns(data.Provider);
            mockSet.As<IQueryable<Stop>>().Setup(m => m.Expression).Returns(data.Expression);
            mockSet.As<IQueryable<Stop>>().Setup(m => m.ElementType).Returns(data.ElementType);
            mockSet.As<IQueryable<Stop>>().Setup(m => m.GetEnumerator()).Returns( data.GetEnumerator());

            _context = new Mock<IWorldContext>();

           //Set the context of mock object to  the data we created.
            _context.Setup(c => c.Stops).Returns(mockSet.Object);

           //Create instance of WorldRepository by injecting mock DbContext we created
            _repo = new WorldRepository(_context.Object);    

                new Stop
                    Arrival = DateTime.Now,
                    Id = 2,
                    Latittude = 0.01,
                    Longitude = 0.005,
                    Name = "Test Trip",
                    Order = 5


            var count = _repo.GetAllTrips().Count();

            Assert.AreEqual(3, count);


Share : facebook icon twitter icon
How do you mock adding items to a repository or DbContext using moq?

How do you mock adding items to a repository or DbContext using moq?

By : Ken
Date : March 29 2020, 07:55 AM
will help you Try to use fake in memory repository instead of moq, for example universal generic repository for all entities:
code :
public interface IInMemoryRepository<T> where T : class
    IQueryable<T> GetAll();
    void Create(T item);
    void Update(T item);
    T GetItem(Expression<Func<T, bool>> expression);
    void Delete(T item);

public class InMemoryRepository<T> : IInMemoryRepository<T> where T : class
    private int _incrementer = 0;
    public Dictionary<int, T> List = new Dictionary<int, T>();

    public IQueryable<T> GetAll()
        return List.Select(x => x.Value).AsQueryable();

    public void Create(T item)
        item.GetType().GetProperties().First(p => p.Name == "Id").SetValue(item, _incrementer, null);
        List.Add(_incrementer, item);

    public void Update(T item)
        var key = (int)item.GetType().GetProperties().First(p => p.Name == "Id").GetValue(item, null);
        List[key] = item;

    public T GetItem(Expression<Func<T, bool>> expression)
        return List.Select(x => x.Value).SingleOrDefault(expression.Compile());

    public void Delete(T item)
        var key = (int)item.GetType().GetProperties().First(p => p.Name == "Id").GetValue(item, null);
Pass mock objects as JUnit parameter to test methods with parameters

Pass mock objects as JUnit parameter to test methods with parameters

By : Ana Luísa Carvalhal
Date : March 29 2020, 07:55 AM
seems to work fine https://github.com/piotrturski/zohhak/blob/master/Full-Guide.md#basic-usage
code :
primitives and their wrappers
BigInteger, BigDecimal (since 1.1.0)
Unit Test Mock Controller, C# Do I need to Mock HTTPContext? What methods do I mock?

Unit Test Mock Controller, C# Do I need to Mock HTTPContext? What methods do I mock?

By : Venkat
Date : March 29 2020, 07:55 AM
may help you .
Question: What methods am I supposed to be mocking and testing within the controller?
code :
    public void SearchforAccount_ReturnSearchAccount()
        var mockAccountsManager = A.Fake<IAccountsManager>();
        var mockCallerInfoManager = A.Fake<ICallerInfoManager>();
        const string SearchTerm = "google"; // Use the passed in parameter in the CallTo setup

        //Define search parameter
        AccountRequest mockAccountRequest = new AccountRequest
            SearchTerm = SearchTerm

        List<Account> expected = new List<Account> { new Account() }; // What we expect to get back

        A.CallTo(() => mockAccountsManager.GetAllWithNameContaining(SearchTerm, A<string>.Ignored)).Returns(expected); // mock the call made in the controller

        using (var accountsController = new AccountController2(mockAccountsManager, mockCallerInfoManager))
            List<Account> returnedAccounts = accountsController.Search(mockAccountRequest);

            Assert.AreSame(expected, returnedAccounts);
public CallerInfo GetFrom(HttpRequest request)
    return ExtractCallerInfo(request.QueryString);

public CallerInfo GetFromHttpContext()
    return GetFrom(HttpContext.Current.Request);
How do I unit test a repository that uses DbContext with NSubstitute?

How do I unit test a repository that uses DbContext with NSubstitute?

By : Yuré Vanderbruggen
Date : March 29 2020, 07:55 AM
this one helps. Well, having driven myself mad trying to do it the way I showed in my question, I came across Effort, which was designed for the task, and followed this tutorial, which got me going. I had a few problems with his code, which I'l explain below.
Briefly, what I did was...
code :
private MyEntities _ctx;
private BaseRepository<Patient> _patientsRepository;
private List<Patient> _patients;

public void Initialize() {
  string connStr = ConfigurationManager.ConnectionStrings["MyEntities"].ConnectionString;
  DbConnection connection = EntityConnectionFactory.CreateTransient(connStr);
  _ctx = new MyEntities(connection);
  _patientsRepository = new BaseRepository<Patient>(_ctx);
  _patients = GetPatients();
public void BaseRepository_Update() {
  Assert.AreEqual(_patients.Count, _patientsRepository.GetAll().Count());

#region Helper methods

private List<Patient> GetPatients() {
  return Enumerable.Range(1, 10).Select(CreatePatient).ToList();

private static Patient CreatePatient(int id) {
  return new Patient {
    ID = id,
    FirstName = "FirstName_" + id,
    Surname = "Surname_" + id,
    Address1 = "Address1_" + id,
    City = "City_" + id,
    Postcode = "PC_" + id,
    Telephone = "Telephone_" + id

private void AddAllPatients() {
  _patients.ForEach(p => _patientsRepository.Update(p));

In C# Unit test how do equivalent of Java's Spy (instead of Mock) to only mock some methods on a class?

In C# Unit test how do equivalent of Java's Spy (instead of Mock) to only mock some methods on a class?

By : user2648096
Date : March 29 2020, 07:55 AM
help you fix your problem With C# mocking frameworks, you do not have a concept like a spy. What you can do is to create a mock and arrange it to call the original code where your method that calls the static method can return the value you desire. You should have in mind that the free C# mocking frameworks will work only with interfaces and virtual methods. So if your case is to arrange a public virtual method that returns a value than here is how this could be done. I will use the free version JustMock for the next examples:
code :
HasSomeStaticCall obj = Mock.Create<HasSomeStaticCall>(Behavior.CallOriginal);
Mock.Arrange(() => obj.callStaticThing()).Returns("SomeValue");

var actual = obj.callStaticThing();

Assert.AreEqual("SomeValue", actual);
HasSomeStaticCall obj = Mock.Create<HasSomeStaticCall>(Behavior.CallOriginal);

Mock.NonPublic.Arrange<string>(obj, "callStaticThingProtected").Returns("SomeValue");
var actual = obj.MethodThatCallsTheProtectedcallStaticThing();

Assert.AreEqual("SomeValue", actual);
Mock.Arrange(() => SomeThirdParty.getFromStaticMethod()).Returns("SomeValue");

HasSomeStaticCall obj = new HasSomeStaticCall();
var actual = obj.Something;

Assert.AreEqual("SomeValue", actual);
Related Posts Related Posts :
  • ASP.NET MVC Html.BeginForm in WebGrid column
  • I need to set value of my ComboBox depending on selection of other ComboBox
  • How to get a result from a stored procedure as value?
  • Can I pass a ValueTuple to a method that requires a generic type and still maintain the member variables?
  • Testing eager-loading scenarios with Effort.EF6
  • Visual studio breaks on exception that IS handled with unhandled exception dialog
  • Cannot get property of class(ASP.NET MVC)
  • NUnit assertions in production code
  • Bug in SSRS CreateFolder C# command?
  • Convert web form content to PDF using c# in asp.net web forms
  • Web Application publishing failed - Visual Studio - C# - ASP.NET
  • How to encode IP for GET request in api in .NET
  • Access class item generated from xml using xsd.exe
  • Is there a shortcut to explicit named paramers when I call a method in C# for VisualStudio 2017?
  • Sorting datatables in a dataset with the datatable.name
  • Datagridview multilpe links
  • Correct pattern for exposing available actions
  • Local web application accepts numbers with comma and published does not
  • How to read an xml file using xmldataprovider in wpf C#
  • Windows service and Entity Framework
  • Visual Studio 2017 Docker support not available for ASP.Net Core Angular or React projects
  • Datacontext models with join
  • WPF: Increased window size decreases performance
  • Handling bad CSV records in CsvHelper
  • C# Displays file icons in asp.net on GridView nested
  • is there a way to get the file names which need to be updated if TFS status.Numoperations != 0?
  • Headless Firefox in Selenium C#
  • How do I start a .exe with a json string as parameter correctly?
  • StreamContent not loaded to the end
  • HAP parses formatting in HTML documents
  • repeat and count a loop in an unordered sequence in C#
  • Redundant Casting in Visual studio
  • Lost references in Visual Studio 2017 solution
  • Is there a way to add two numbers using a private constructor in C#
  • Is it possible to execute multiple SSH commands from a single login session with SSH.NET?
  • How can I get NHibernate to map to a Tuple or Class?
  • MVC 5 C# Window Authentication pop up when I navigate to a certain area
  • Mongo C# driver toJson() DateTime
  • Coprime integers
  • What is the purpose with files ending with *CS.cs in Xamarin Forms projects?
  • MVC5 / Entity | Update/Create Complex Model
  • How to return auto increment ID from SQL using Petapoco ORM in .NET MVC
  • Create new web app offline c# using Visual Studio
  • How many times is ordered the IEnumerable in this case?
  • C# error when update database 2008 to sql 2016
  • How to insert string in multiple continuous pattern in windows c#
  • How to send temp data from Partial View to its parent View
  • C# encapsulation when getting updates from asynchronous method
  • Asp net core Content Security Policy implementation
  • @Html.DropDownList() Placeholder as Disable and Selected
  • Set AM/PM in Material Time Picker WPF
  • Ninject passing reference in constructor
  • C# Entity Framework text SQL query wrapper
  • Core 2.0 MVC - AD Group Authorization for logging
  • Decentralized NLog Target per Http request
  • How to use x:Object and when?
  • Displays file icons in asp.net on GridView
  • How do I avoid two (or more) threads that work on a table at the same time to not work on same row?
  • Add xml attribute for property in DB First
  • How do i execute 2 sql queries by clicking a button [C#]
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org