How to mock SetCommandTimeout and optionsBuilder using moq in .Net Core API RRS feed

  • Question

  • I need a help to mock and handle the SetCommandTimeout and optionsBuilder  for unit testing using Moq and NBuilder possibly?

    Database Context: 

    public class ImportContext : DbContext, IImportContext
    		public ImportContext()
    		protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    			optionsBuilder.UseSqlServer(new WebServiceAppSettings().ConnectionString);
    		public DbContext GetContext(Type dataContextType)
    			return (DbContext)Activator.CreateInstance(dataContextType);
    		public DbSet<Data> Data { get; set; }
    		public DbSet<SerialNum> SerialNum { get; set; }


    public int GetSerialNo()
    				using (var context = new ImportContext())
    					var result = context.SerialNum.FirstOrDefault(p => p.SerialType == SerialNumType);
    					if (result != null)
    						var newHcpDataId = (Convert.ToInt32(result.SerialId) + 1);
    						result.SerialId = newDataId.ToString();
    						return newDataId;
    					return 0;
    			catch (Exception ex)
    				throw ex;


    using System.Linq;
    using FizzWare.NBuilder;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using Moq;
    using Services.Import.DBContext;
    using Services.Import.Entities;
    using Services.Import.Service;
    using Services.Import.Test.Helper;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore.Storage;
    namespace Services.Import.Test.Services
        public class ImportServiceTest
            private Mock<IEmailService> _mockEmailService;
            private Mock<IUtilityService> _mockUtilityService;
            private Mock<IImportContext> _mockImportContext;
            private ImportService _ImportService;
            private readonly RandomGenerator _random = new RandomGenerator();
            private readonly Mock<IImportContext> _mockContextFactory = new Mock<IImportContext>();
            public void TestSetup()
                _mockImportContext = new Mock<IImportContext>();
                _mockEmailService= new Mock<IEmailService>();
                _mockUtilityService = new Mock<IUtilityService>();
                _ImportService = new ImportService(_mockImportContext.Object, _mockUtilityService.Object, _mockEmailService.Object);
            public void GetSerialNo_WhenItCalled_ShouldFindSerialNo()
                // Arrange
                var expectedResult =  _random.Int();
                var serialNum = Builder<SerialNum>.CreateListOfSize(5).All().Build();
                _mockImportContext.Setup(mc => mc.SerialNum).Returns(ContextExtension.GetQueryableMockDbSet(serialNum.ToList()));
                //Mock<Database> mockdatabase= new Mock<Database>("", _mockImportContext.Object);
                // Act
                var actualResult = _ImportService.GetSerialNo();
                // Assert
                Assert.AreEqual(expectedResult, actualResult);

    When i execute the test for the case GetSerialNo_WhenItCalled_ShouldFindSerialNo it fails as it is missing the environment for SetCommandTimeout and optionsBuilder. When i comment those two my test is working fine.

    Teaching me on how to mock the above test without any code changes in the DBContext will be really grateful. 

    Thank you for your support in advance. 


    SomaSundaram R

    Friday, November 22, 2019 10:37 AM

All replies

  • Hi SomaSundaram R,

    Welcome to MSDN forum.

    According to your description, I searched for some data and it seems hard to do this by using “mock”.

    I’m not sure if “InMemory” could help you. As far as I know you will be able to set options by using it, but it needs Xunit framework. If possible, maybe you could refer to this document: Testing with InMemory.

    I hope this could help you.



    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, November 25, 2019 7:49 AM