Created
September 29, 2013 02:40
-
-
Save aikmeng/6748867 to your computer and use it in GitHub Desktop.
Allow unit test by mocking up dbcontext and dbset.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace ExperimentMoq | |
{ | |
public class DbEntity | |
{ | |
public int Id { get; set; } | |
public string Name { get; set; } | |
} | |
public class CustomDbContext : DbContext, IDisposable | |
{ | |
public virtual IDbSet<DbEntity> DbEntities { get; set; } | |
} | |
public class Processor | |
{ | |
private readonly CustomDbContext _dbContext; | |
public Processor(CustomDbContext dbContext) | |
{ | |
_dbContext = dbContext; | |
} | |
public DbEntity Find(int id) | |
{ | |
return _dbContext.DbEntities.FirstOrDefault(dbEntity => dbEntity.Id == id); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace ExperimentMoq.Test | |
{ | |
[TestClass] | |
public class ProcessorTest | |
{ | |
[TestMethod] | |
public void TestFind() | |
{ | |
//Arrange | |
const int expectedId = 1; | |
var expected = new DbEntity { Id = expectedId, Name = "Entity 1" }; | |
var data = new List<DbEntity> | |
{ | |
expected, | |
new DbEntity { Id = 2, Name = "Entity 2" }, | |
new DbEntity { Id = 3, Name = "Entity 3" }, | |
new DbEntity { Id = 4, Name = "Entity 4" } | |
}.AsQueryable(); | |
var dbSetMock = new Mock<IDbSet<DbEntity>>(); | |
dbSetMock.Setup(m => m.Provider).Returns(data.Provider); | |
dbSetMock.Setup(m => m.Expression).Returns(data.Expression); | |
dbSetMock.Setup(m => m.ElementType).Returns(data.ElementType); | |
dbSetMock.Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator()); | |
var customDbContextMock = new Mock<CustomDbContext>(); | |
customDbContextMock | |
.Setup(x => x.DbEntities) | |
.Returns(dbSetMock.Object); | |
var classUnderTest = new Processor(customDbContextMock.Object); | |
//Action | |
var actual = classUnderTest.Find(expectedId); | |
//Assert | |
Assert.IsNotNull(actual); | |
Assert.AreEqual(expected.Id, actual.Id); | |
Assert.AreEqual(expected.Name, actual.Name); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment