我正在尝试在我的示例项目中进行测试,当我断言删除的对象是否为null(Assert.IsNull失败)时,我收到错误。
我正在使用Microsoft Visual Studio 2010,Entity Framework 4.3.1和常规Moq。
以下是我正在使用的代码:
服务:
private ClientRepository rep;
public ClientService(MyContext ctx)
{
this.rep = new ClientRepository(ctx);
}
public void Delete(Client client)
{
try
{
rep.Delete(client);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
throw new Exception("error");
}
}
public Client GetById(int Id)
{
return rep.GetById(Id);
}
存储库:
private MyContext _dbContext;
public ClientRepository(MyContext ctx)
{
_dbContext = ctx;
}
public void Delete(Client client)
{
Client cl = _dbContext.Clients.Where(x => x.Id == client.Id).FirstOrDefault();
if (cl != null)
{
_dbContext.Clients.Remove(client);
_dbContext.SaveChanges();
}
else
{
throw new Exception("Client does'n exist");
}
}
public Client GetById(int Id)
{
return _dbContext.Clients.Where(x => x.Id == Id).FirstOrDefault();
}
我的删除测试:
[TestMethod]
public void MockDelete()
{
//arrange
var data = new List<Client>
{
new Client(){
Id = 1,
Name = "asdfg"
}
}.AsQueryable();
var dbSetMock = new Mock<IDbSet<Client>>();
var myContextMock = new Mock<MyContext>();
dbSetMock.As<IQueryable<Client>>().Setup(m => m.Provider).Returns(data.Provider);
dbSetMock.As<IQueryable<Client>>().Setup(m => m.Expression).Returns(data.Expression);
dbSetMock.As<IQueryable<Client>>().Setup(m => m.ElementType).Returns(data.ElementType);
dbSetMock.As<IQueryable<Client>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());
myContextMock.Setup(m => m.Clients).Returns(dbSetMock.Object);
var service = new ClientService(myContextMock.Object);
//act
var classtodelete = data.First(m => m.Id == 1);
service.Delete(classtodelete);
string name = service.GetById(1).Name;
//assert
dbSetMock.Verify(m => m.Remove(It.IsAny<Client>()), Times.Once());
myContextMock.Verify(m => m.SaveChanges(), Times.Once);
Assert.IsNull(name);
}
我的目标是测试我的服务的业务规则(我没有放在这里),也许我嘲笑错误的课程,或者我错过了什么,我希望有人可以帮助我。