Unit testing with Effort - entity-framework

I'm currently trying to unit test an context class of the Entity Framework with the "Effort" framework (http://effort.codeplex.com/wikipage?title=Tutorials&referringTitle=Home).
This is how my test currently looks:
[TestMethod]
public void GetUseraccountsForRealTest()
{
DbConnection connection = Effort.DbConnectionFactory.CreateTransient();
SqlContext context = new SqlContext(connection);
context.TaskComment.Add(new TaskComment() { Id = 1, Message = "Test" });
}
The last line isn't working. Nothing happens.
This is how my SqlContext class looks:
public class SqlContext : DbContext
{
...
public IDbSet<TaskComment> TaskComment { get; set; }
...
//Constructor used by webserver
public SqlContext(string connectionString) : base(connectionString)
{
}
//Constructor used for unit testing
public SqlContext(DbConnection connection) : base(connection, true)
{
this.Configuration.LazyLoadingEnabled = false;
}
///
/// <param name="modelBuilder"></param>
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}
}
Anyone got an idea how I can solve this problem? Don't have any experience with "Effort" and there's not too much documentation. :-(

Solved the problem on my own.
I didn't use IDbSet in my context, butt just DbSet which lead to some difficulties.

Related

Database Migration on Startup

I've read a lot of articles regarding database migration on startup and no matter what approach I use my efforts aren't going anywhere. My main problem that i'm getting is no parameterless constructor defined for type startup
I have my DataContext class
public class DataContext : DbContext
{
public DataContext(DbContextOptions options) : base(options)
{
}
public DataContext()
{
}
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
if (options.IsConfigured)
{
//means that context has been added during dependency injection and no further action required.
}
else
{
//means context is being accessed during Add-Migration therefore we need to set the options. The whole DI/Configuration process won't have run yet, so need some other way to get connection string.
//probably below is a bit too fancy, just hardcoding would be fine. But anyway it seems to work and transfers to different developers machines
//you must have {Values: { SqlConnectionString : xyz}} in local.settings.json in Unite.FunctionApp project dir
var localSettingsJson =
Path.Combine(local.settings.json");
var config = new ConfigurationBuilder()
.AddJsonFile(localSettingsJson, false)
.Build();
options.UseSqlServer(config["Values:SqlConnectionString"]);
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{... }
My Startup Class
// register assembly
[assembly: FunctionsStartup(typeof(Startup))]
{
// inherit FunctionsStartup
public class Startup : FunctionsStartup
{
private DataContext _context;
public Startup(DataContext context)
{
_context = context;
}
public override void Configure(IFunctionsHostBuilder builder)
{
var executionContextOptions = builder.Services.BuildServiceProvider()
.GetService<IOptions<ExecutionContextOptions>>().Value;
var config = new ConfigurationBuilder()
.SetBasePath(executionContextOptions.AppDirectory)
.AddJsonFile("local.settings.json", true)
.AddUserSecrets(Assembly.GetExecutingAssembly(), false)
.AddEnvironmentVariables()
.Build();
builder.Services.AddSingleton<IConfiguration>(config);
var sqlConnection = config["SqlConnectionString"] ??
throw new Exception("SQL Connection String Not Defined");
builder.Services.AddDbContext<DataContext>(options => options.UseSqlServer(sqlConnection));
_context.Database.MigrateAsync();
}
}
}
If I have my paramaterless DataContext method in my class why am i still getting this issue that it isn't defined?
Add your parameterless constructor before the other constructor in your DataContext class.

Dbcontext not able to migrate because schema does not exist?

I am currently writing some integrations test which affect the database just in a different schema.
I am following this guide
https://www.thinktecture.com/en/entity-framework-core/isolation-of-integration-tests-in-2-1/
My problem is with this abstract class used for creating DbContext?
public abstract class IntegrationTestsBase<T> : IDisposable
where T : DbContext
{
private readonly string _schema;
private readonly string _historyTableName;
private readonly DbContextOptions<T> _options;
protected T DbContext { get; }
protected IntegrationTestsBase()
{
_schema = Guid.NewGuid().ToString("N");
_historyTableName = "__EFMigrationsHistory";
_options = CreateOptions();
DbContext = CreateContext();
DbContext.Database.Migrate();
}
protected abstract T CreateContext(DbContextOptions<T> options,
IDbContextSchema schema);
protected T CreateContext()
{
return CreateContext(_options, new DbContextSchema(_schema));
}
private DbContextOptions<T> CreateOptions()
{
return new DbContextOptionsBuilder<T>()
.UseNpgsql($"Server=(local);Database=Demo;...",
builder => builder.MigrationsHistoryTable(_historyTableName, _schema))
.ReplaceService<IMigrationsAssembly, DbSchemaAwareMigrationAssembly>()
.ReplaceService<IModelCacheKeyFactory, DbSchemaAwareModelCacheKeyFactory>()
.Options;
}
public void Dispose()
{
DbContext.GetService<IMigrator>().Migrate("0");
DbContext.Database.ExecuteSqlCommand(
(string)$"DROP TABLE [{_schema}].[{_historyTableName}]");
DbContext.Database.ExecuteSqlCommand((string)$"DROP SCHEMA [{_schema}]");
DbContext?.Dispose();
}
}
DbContext is being created, but once the migrations is being called i get an error stating that the schema, does not exist?
which I am not sure why because i in my ensure the in my configuration
public class SchemaContext : DbContext, IDbContextSchema
{
public virtual DbSet<Schema>? SchemaModel { get; set; }
public SchemaContext()
{
}
public SchemaContext(DbContextOptions<SchemaContext> options, IDbContextSchema schema = null)
: base(options)
{
Schema = schema.Schema;
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema(Schema);
//base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
}
public string Schema { get; }
}
I would assume that modelBuilder.HasDefaultSchema(Schema); would have created the schema?
which does not seem to be case, hence migration fails? what am I missing? why is the schema not being created in the actual database?
In your could you are configure Context with method - UseSqlServer which is used only for MS SQL, you have to use Npgsql.EntityFrameworkCore.PostgreSql package and configure you context with UseNpgsql extension method:
.UseNpgsql("Host=localhost;Port=5432;Database=my_db;Username=postgres;Password=password");

No extension Method ToList on a dbset - really though?

Background - I am using Entity framework code version 2.1.4-rtm-31024
check out the CODE LISTING 1 - the problem (according to Ms Build Engine 15.9) is that GetAllMakes calls .ToList, but no 'ToList' method exists for a DbSet of VehicleMake. (check out Code Listing 2) to see the implementation of _vehicleContext.VehicleMakes
Why do I get a compile error? this makes no sense to me since I can call VehicleMakes.ToList() elsewhere in the code (no compiler error) no problem at all - see listing 3 for an example.
CODE LISTING 1
using System.Collections.Generic;
namespace CarPriceComparison.Models
{
public class VehicleRepository : IVehicleRepository
{
private VehicleContext _vehicleContext;
public VehicleRepository(VehicleContext dbContext_)
{
_vehicleContext = dbContext_;
}
public IEnumerable<VehicleMake> GetAllMakes()
{
return _vehicleContext.VehicleMakes.ToList();
}
}
}
CODE LISTING 2
namespace CarPriceComparison.Models
{
public class VehicleContext : DbContext
{
private IConfigurationRoot _config;
public VehicleContext(IConfigurationRoot config_, DbContextOptions
options_) : base(options_)
{
_config = config_;
}
public DbSet<VehicleMake> VehicleMakes {get; set;}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.UseSqlServer(_config["ConnectionStrings:VehicleContextConnection"]);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<VehicleModel>()
.HasOne(p => p.Make)
.WithMany(b => b.Models)
.HasForeignKey(p => p.VehicleMakeForeignKey)
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);
}
}
}
CODE LISTING 3
private VehicleContext _vehicleContext;
private IMailService _mailService;
private IConfigurationRoot _config;
public HomeController(IMailService mailService_, IConfigurationRoot
config_, VehicleContext vehicleContext_)
{
_vehicleContext = vehicleContext_;
_mailService = mailService_;
_config = config_;
}
public IActionResult Index()
{
var vehicleData = _vehicleContext.VehicleMakes.ToList();
return View();
}
I think you missing an using statement.
using System.Linq;

How to Resolve multiple DBContext call using generic UnitOfWork<TContext> in Autofac

Hi I have created my UnitOfWork as generic and at runtime it should create new instance of DB context with DBContextOption Builder on the basis of TContext passing I have registered Mention DB Context in autofac but how to resolve this at DB Context Constructor Level
DB Context 1 Implemetation
public class DBContext1 : DbContext
{
public DBContext1(DbContextOptions<DBContext1> options1) : base(options1)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
DB Context 2 Implemetation
public class DBContext2 : DbContext
{
public DBContext2(DbContextOptions<DBContext2> options2) : base(options2)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
IUnitOfWork interface Implemetation
public interface IUnitOfWork<TContext> where TContext : DbContext, IDisposable
{
}
UnitOfWork class Implemetation
public class UnitOfWork<TContext> : IDisposable, IUnitOfWork<TContext> where TContext : DbContext, new()
{
private DbContext _context;
public UnitOfWork()
{
_context = new TContext();
}
}
StartUp Class Implemetation
public class Startup
{
protected IConfiguration _configuration { get; set; }
public Startup(IConfiguration configuration)
{
_configuration = configuration;
}
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddEntityFrameworkSqlServer()
.AddDbContext<DBContext1>(options =>
options.UseSqlServer(_configuration.GetConnectionString("DBContext1")))
.AddDbContext<DBContext2>(options =>
options.UseSqlServer(_configuration.GetConnectionString("DBContext2")));
/* Autofac DI Configuration with registering DBContext/DataModule/ServiceModule to it */
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterInstance(_configuration).AsImplementedInterfaces().ExternallyOwned();
var autoFacOptions1 = new DbContextOptionsBuilder<DBContext1>().UseSqlServer(_configuration.GetConnectionString("DBContext1")).Options;
var autoFacOptions2 = new DbContextOptionsBuilder<DBContext2>().UseSqlServer(_configuration.GetConnectionString("DBContext2")).Options;
containerBuilder.Register(c => new DBContext1(autoFacOptions1)).As<DbContext>();
containerBuilder.Register(c => new DBContext2(autoFacOptions2)).As<DbContext>();
containerBuilder.RegisterModule<DataModule>();
containerBuilder.RegisterModule<ServiceModule>();
containerBuilder.Register<String>(c => Guid.NewGuid().ToString())
.Named<String>("correlationId")
.InstancePerLifetimeScope();
containerBuilder.Populate(services);
var container = containerBuilder.Build();
return new AutofacServiceProvider(container);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Account}/{action=Login}/{id?}");
});
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
}
I am able to achieve multiple DBContext Call as required but I have to create Default constructor & connection string in DB context like mention below
DB Context 1 Implemetation
public class DBContext1 : DbContext
{
public DBContext1()
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(#"Data Source=Server;Database=DB;User Id=UserID;Password=Password;Integrated Security=False;MultipleActiveResultSets=true;");
}
public DBContext1(DbContextOptions<DBContext1> options1) : base(options1)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
DB Context 2 Implemetation
public class DBContext2 : DbContext
{
public DBContext2()
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(#"Data Source=Server;Database=DB;User Id=UserID;Password=Password;Integrated Security=False;MultipleActiveResultSets=true;");
}
public DBContext2(DbContextOptions<DBContext2> options2) : base(options2)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
Please help me to call parameterised constructor of DBContext1 & DBContext2 using autofac dependency resolver
Well, if you're using autofac to resolve dependencies then why are you trying to do its job for it? :) That's the main problem with your code.
First of all, you don't need to register IConfiguration explicitly. It is already registered in the IServiceCollection that's passed to ConfigureServices() method and will be automatically picked up by autofac during containerBuilder.Populate(services) call. You can just remove this registration and nothing will change.
Further, you're registering both your DbContexts twice - in the service collection and in the autofac container builder. This is not necessary as the latter will effectively replace the former. Also, it creates confusion about what is registered where and how this whole this is going to work. It's better to pick one method of registration and stick with it.
Next problem: how are you going to unit test your unit of work? It has hard dependency on DbContext whose lifecycle you cannot control in tests. This is exactly what you need autofac for: manage component's dependencies for you allowing you to concentrate on the component's purpose and not on the secondary stuff.
Next confusion point is here:
containerBuilder.Register(c => new DBContext1(autoFacOptions1)).As<DbContext>();
containerBuilder.Register(c => new DBContext2(autoFacOptions2)).As<DbContext>();
By doing this you are effectively replacing first db context registration with the second. From this point there is no way to inject DBContext1 anywhere in your application. EDITED: You still can inject collection of DbContext derivative implementations and find DBContext1 among them... but that would look very weird.
All in all, this can be done in much more clean and straightforward way.
Startup
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddMvc();
var builder = new ContainerBuilder();
builder.Register(c => c.CreateDbContextOptionsFor<DBContext1>("DBContext1")).As<DbContextOptions<DBContext1>>().SingleInstance();
builder.Register(c => c.CreateDbContextOptionsFor<DBContext2>("DBContext2")).As<DbContextOptions<DBContext2>>().SingleInstance();
builder.RegisterType<DBContext1>().AsSelf().InstancePerLifetimeScope();
builder.RegisterType<DBContext2>().AsSelf().InstancePerLifetimeScope();
builder.RegisterType<SomeComponent>().As<ISomeComponent>().InstancePerLifetimeScope();
builder.RegisterGeneric(typeof(UnitOfWork<>)).As(typeof(IUnitOfWork<>)).InstancePerLifetimeScope();
builder.Populate(services);
var container = builder.Build();
return new AutofacServiceProvider(container);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
....
}
}
CreateDbContextOptionsFor helper implementation. It is introduced in order to make Startup code concise and more readable. It can probably be improved even further by making use of autofac's parameterized factory instead of new DbContextOptionsBuilder<TContext>(), but I'm not sure if there's a point in it in this case.
public static class DBExtentions
{
public static DbContextOptions<TContext> CreateDbContextOptionsFor<TContext>(this IComponentContext ctx,
string connectionName) where TContext : DbContext
{
var connectionString = ctx.Resolve<IConfiguration>().GetConnectionString(connectionName);
return new DbContextOptionsBuilder<TContext>().UseSqlServer(connectionString).Options;
}
}
UnitOfWork
public class UnitOfWork<TContext> : IUnitOfWork<TContext> where TContext : DbContext
{
private TContext _context;
public UnitOfWork(TContext context)
{
_context = context;
}
}
Injecting and using unit of work
public class SomeComponent : ISomeComponent
{
private readonly IUnitOfWork<DBContext1> _uow;
public SomeComponent(IUnitOfWork<DBContext1> uow)
{
_uow = uow;
}
public void DoSomething()
{
_uow.DoWhatever();
}
....

MsTest - Mocking a DbContext with DbContextOption and configuration

I have 2 project, Data and Data.test, I use ef core and .net core for both of them, for Data project I have ExpenseDb like this:
public class ExpenseDb: DbContext
{
private IConfigurationRoot _config;
public ExpenseDb(DbContextOptions<ExpenseDb> options, IConfigurationRoot config) : base(options)
{
_config = config;
}
public DbSet<Account> Accounts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.UseSqlServer(_config["Data:ConnectionString"]);
}
}
And I have a repository for Account like this:
private ExpenseDb _db;
public AccountRepository(ExpenseDb db)
{
_db = db;
}
public IEnumerable<Account> All(Guid userId)
{
return (_db.Accounts.AsNoTracking().Where(a => a.UserId == userId).ToList());
}
I use ms IOC for injectiong dependencies like this :
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json");
_config = builder.Build();
}
IConfigurationRoot _config;
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton(_config);
services.AddDbContext<ExpenseDb>(ServiceLifetime.Scoped);
}
These all are in my Data project, and for Data.Test I would like to test All method, I realized I must Mock my ExpenseDb so I got Moq from Nuget Package and now I have test class like this :
[TestClass]
public class AccountRepositoryTest
{
private readonly Mock<ExpenseDb> _dbMock = new Mock<ExpenseDb>();
private readonly AccountRepository _repo;
public AccountRepositoryTest()
{
_repo = new AccountRepository(_dbMock.Object);
}
[TestMethod]
public void AllForInvalidUser()
{
var fakeaccount = new Account() { Name="cat2",OpenDate=DateTime.Now,StartBalance=100};
Mock < DbSet < Account >> acMock = DbSetMock.Create(fakeaccount);
var results = _repo.All(Guid.Parse("cf15c6c9-f688-47ee-892e-297e530be053"));
Assert.IsNotNull(results);
}
}
Obviously my test is failed, because I must pass config and options to my ExpenseDb somehow, but I don't know How?!
I searched and I found out all answer are saying "You must have an inteface for your service" but i don't want to create an unnecessary interface.
Since DbContextOptions and config are not being used in the actual test code. You could create a constructor in your db context marked as protected to allow the instantiation of the ExpenseDb object without any params.