[英]N-Tier Architecture WebApi: NUnit - No suitable constructor was found
我對這個單元測試和 NUnit 測試非常陌生。 當我嘗試運行以下代碼時...出現以下錯誤
namespace NC_BLUnitTests
{
[TestFixture]
public class ProductBLTests
{
private IBLProductsRepo blRepo;
public ProductBLTests(IBLProductsRepo _blRepo)
{
blRepo = _blRepo;
}
[Test]
public void AddProduct_Test()
{
//Arrange
var expectedResult = new ProductVM()
{
Name = "prod 4",
CreatedDateTime = DateTime.Now,
Price = 65.89m,
Status = (int)StatusEnm.Active
};
// Act
int resId = blRepo.AddProduct(expectedResult).Result.Data;
var res = blRepo.GetProduct(resId);
// Assert
Assert.Equals(expectedResult, res);
}
}}
沒有找到合適的構造函數
現在,我在這里搜索了很多文章,但我什么都不懂。
這是我正在嘗試測試的業務層代碼
namespace NC_BLRepositories {
public class BLProductsRepo : IBLProductsRepo
{
private IDLProductsRepo dlProductsRepo;
public BLProductsRepo(IDLProductsRepo dlRepo)
{
dlProductsRepo = dlRepo;
}
public Task<Response<int>> AddProduct(ProductVM product)
{
Response<int> res = new Response<int>();
try
{
res.Data = dlProductsRepo.AddProduct(product).Result;
res.IsSuccess = true;
res.Message = "Product Added Successfully";
}
catch (Exception ex)
{
res.IsSuccess = false;
res.Message = "Some Error While Adding Product: " + ex.Message;
}
return Task.FromResult(res);
}
public Task<Response<ProductVM>> GetProduct(int productId)
{
Response<ProductVM> res = new Response<ProductVM>();
try
{
res.IsSuccess = true;
res.Message = "Product fetched successfully";
res.Data = new ProductVM(dlProductsRepo.GetProduct(productId).Result);
if (res.Data?.Id == 0)
res.Message = "Invalid Product";
}
catch (Exception ex)
{
res.IsSuccess = false;
res.Message = "Some Error While Fetching Single Product: " + ex.Message;
}
return Task.FromResult(res);
}
}}
這是在這里注入的數據層,將來會進行測試。
namespace NC_DLRepositories {
public class DLProductsRepo : IDLProductsRepo
{
private MyShopContext dbCtx;
public DLProductsRepo(MyShopContext ctx)
{
dbCtx = ctx;
}
public async Task<int> AddProduct(Product product)
{
Product newProduct = product;
dbCtx.Products.Add(newProduct);
await dbCtx.SaveChangesAsync();
return newProduct.Id;
}
public async Task<Product> GetProduct(int productId)
{
return await dbCtx.Products.Where(e => e.Id == productId).SingleOrDefaultAsync();
}
}}
請指導我,我對所有這些事情的了解都是 0,互聯網只給了我所有的基本文章。
錯誤在於您的 TestFixture 在其構造函數中需要IBLProductsRepo
類型的參數,但未提供任何參數。
默認情況下,當沒有給出參數時,NUnit 會嘗試使用默認構造函數,因此消息表明沒有默認構造函數。 這有點誤導,因為你真的想提供一個論點。
以各種方式向 NUnit TestFixtures 提供參數。 最簡單的方法是使用[TestFixture(ARG)]
但在 C# 中對於非原始類 Type 是不允許的。 接下來最好使用[TestFixtureSource("xxx")]
,其中 xxx 是返回IEnumerable<IBLProductsRepo>
的靜態字段、屬性或方法的名稱。
或者,如果您對所有測試使用相同的 repo,請刪除參數並將其設置為單例,以供測試訪問。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.