我在爲如何編寫我的web api的單元測試而失去id方法的GET。Web API的單元測試,GET相同的ID
以下是我有:
public void GetProduct_ShouldReturnSameID()
{
var context = new TestModelContext();
context.Products.Add(GetDemoProduct());
var controller = new ProductsController(context);
var result = controller.GetProduct(3) as OkNegotiatedContentResult<Product>;
Assert.IsNotNull(result);
Assert.AreEqual(3, result.Content.Id);
}
而且我的控制器方法我試圖測試
public IHttpActionResult GetProduct(int id)
{
var product = (from t in db.Products.Include(t => t.Reviews)
.Where(t => t.Id == id)
select t);
if (product == null || product.Count() == 0)
{
return NotFound();
}
return Ok(product);
}
我的測試工作找到我的其他控制器,但只是沒有這一個。我想知道這有什麼問題?我的測試失敗與
「預期:不爲空,但被:空」
public class TestModelContext : IModelContext {
public TestModelContext() {
this.Products = new TestProductDbSet();
}
public DbSet<Product> Products { get; set; }
public int SaveChanges() {
return 0;
}
public void MarkAsModified(Product item) { }
public void Dispose() { }
}
public class TestProductDbSet : TestDbSet<Product> {
public override Product Find(params object[] keyValues) {
return this.SingleOrDefault(product => product.Id == (int)keyValues.Single());
}
}
public class TestDbSet<T> : DbSet<T>, IQueryable, IEnumerable<T>
where T : class
{
ObservableCollection<T> _data;
IQueryable _query;
public TestDbSet()
{
_data = new ObservableCollection<T>();
_query = _data.AsQueryable();
}
// ...
public override T Create()
{
return Activator.CreateInstance<T>();
}
public override TDerivedEntity Create<TDerivedEntity>()
{
return Activator.CreateInstance<TDerivedEntity>();
}
public override ObservableCollection<T> Local
{
get { return new ObservableCollection<T>(_data); }
}
Type IQueryable.ElementType
{
get { return _query.ElementType; }
}
System.Linq.Expressions.Expression IQueryable.Expression
{
get { return _query.Expression; }
}
IQueryProvider IQueryable.Provider
{
get { return _query.Provider; }
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return _data.GetEnumerator();
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return _data.GetEnumerator();
}
}
GetDemoProduct:
Product GetDemoProduct()
{
return new Product() { Id = 3, Name = "Name", Reviews = null };
}
您的'TestModelContext'是否具有到數據庫的實際連接或是否是內存中的上下文?我猜你的linq查詢中的'Include'可能導致'product'變量爲'null' – Nkosi
用我的'TestModelContext'更新了 – mimickd
ok,雖然這顯示了一些更多的信息,我們還需要看'TestProductDbSet'因爲這是查詢將執行的對象 – Nkosi