Unit Testing Entity Framework Core

Asked

Viewed 26 times

0

Hello, I am starting a project and it is the first time I work with unit test, we are trying to perform unit test in EF Core, but when testing the Get, I am not able to get the value of _companyService, follow the test code, I had a dependency injection and I think that’s why I’m not getting it.

public class EmpresaTest
    {
        private readonly IEmpresaService _empresaService;

        public EmpresaTest()
        {
            var service = new ServiceCollection();
            service.AddDbContext<VetorPDVContext>((s, o) => o.UseInMemoryDatabase("pdvDI").EnableSensitiveDataLogging());
            service.AddScoped<VetorPDVContext, VetorPDVContext>();
            service.AddTransient<IEmpresaRepository, EmpresaRepository>();
            service.AddTransient<IEmpresaService, EmpresaService>();
            service.AddTransient<IEmpresaAppService, EmpresaAppService>();

            var provider = service.BuildServiceProvider();
            _empresaService = provider.GetService<IEmpresaService>();

            

            InitContext();
        }

        public void InitContext()
        {
            var controller = new EmpresaAppService(_empresaService);
            var empresa = new EmpresaModel { CodigoEmpresa = 1, CgcEmpresa = "00000000/0000-00", RazaoSocial = "Empresa 01", NomeFantasia = "Empresa 01" };
            controller.Add(empresa);
        }
        [Fact]
        public void TestGetAsync()
        {
           var result = _empresaService.Get(emp => emp.CodigoEmpresa == 1).Result.ToList();
        }
    }

1 answer

0

What happens is that you seem to be actually going to the bank, which makes no sense, the test should be done to what refers to the method. If you don’t know, I suggest you make a mock of the service, this way you manipulate the expected test results for any part of your service. I use Moq, there is a lot of material available on it.

Nuget Moq

Browser other questions tagged

You are not signed in. Login or sign up in order to post.