我剛開始用的單元測試播放嘲笑使用/起訂量,並遇到了一個問題..C#+模擬服務層?
我已經下面的代碼名爲「爲CustomerService」服務層:
public interface ICustomerService
{
Customer GetCustomerById(int id);
}
public class CustomerService : ICustomerService
{
private IRepository<Customer> customerRepository;
public CustomerService(IRepository<Customer> rep)
{
customerRepository = rep;
}
public Customer GetCustomerById(int id)
{
var customer = customerRepository.Get(x => x.CustomerId == id);
if (customer == null)
return null;
return customer;
}
}
我的倉庫類是通用的,是以下幾點:
public interface IRepository<T> : IDisposable where T : class
{
T Get(Expression<Func<T, bool>> predicate);
}
public class Repository<T> : IRepository<T> where T : class
{
private ObjectContext context;
private IObjectSet<T> objectSet;
public Repository()
: this(new demonEntities())
{
}
public Repository(ObjectContext ctx)
{
context = ctx;
objectSet = context.CreateObjectSet<T>();
}
public T Get(Expression<Func<T, bool>> predicate)
{
T entity = objectSet.Where<T>(predicate).FirstOrDefault();
if (entity == null)
return null;
return objectSet.Where<T>(predicate).FirstOrDefault();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (context != null)
{
context.Dispose();
context = null;
}
}
}
}
現在是我的問題。我怎樣才能讓單元測試來檢查我是否GetCustomerById返回空或不是?
已經嘗試過:
[TestMethod]
public void GetCustomerTest()
{
const int customerId = 5;
var mock = new Mock<IRepository<Customer>>();
mock.Setup(x => x.Get(z => z.CustomerId == customerId))
.Returns(new Customer());
var repository = mock.Object;
var service = new CustomerService(repository);
var result = service.GetCustomerById(customerId);
Assert.IsNotNull(result);
}
沒有運氣...
通過傳遞模擬庫。使用不在模擬存儲庫中的ID進行調用。順便說一句,這是沒有太多的測試.... – 2010-10-17 11:09:42
已經嘗試過,沒有運氣... – ebb 2010-10-17 11:12:13