Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Testing IdentityContext

I've recently rewritten an MVC 4 app as MVC 5, so that I can use ASP.NET identity. My old tests were set up as follows (I have no connection string in the test project)

context:

public class MyDbContext: DbContext {
public MyDbContext() : base("name=DefaultContext") {}...

test:

var mockVoteSet = new Mock<DbSet<Vote>>();

var mockContext = new Mock<MyDbContext> { CallBase = true };
mockContext.Setup(c => c.Votes).Returns(mockVoteSet.Object);        

var service = new VoteService(mockContext.Object);

var result = service.Vote(1, "1", false);    
//then assert result

This was working well, and all my tests were passing.

Since moving over my context now inherits from IdentityDbContext:

public class MyDbContext: IdentityDbContext<User> {       
        public MyDbContext() : base("name=DefaultContext") { } ...

I now get an error when passing a mock of the context to the service in the test:

No connection string named 'DefaultContext' could be found in the application config file.

How can I get around this?

like image 514
woggles Avatar asked Dec 11 '25 19:12

woggles


1 Answers

Already tried something like this?

Public interface IMyDbContext
{
    DbSet Votes { get; set;}
    void SaveChanges();
}

Public class MyDbContext : IdentityDbContext<User> , IMyDbContext
{
    Public DbSet Votes { get; set;}
    Public void SaveChanges(){
      //...
    }

}

var mockVoteSet = new Mock<DbSet<Vote>>(){ CallBase = true };
var _context = new Mock<IMyDbContext>(MockBehavior.Strict);
_context.Setup(c => c.Votes).Returns(mockVoteSet.Object); 

var service = new VoteService(_context.Object);
like image 160
alessandro Avatar answered Dec 16 '25 02:12

alessandro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!