【发布时间】:2021-07-06 18:07:58
【问题描述】:
我的项目需要单元测试。我在我的控制器中使用构造函数依赖注入。当我在我的单元测试项目中模拟注入的依赖对象并在测试方法中调用它时。在所有情况下都返回 null。
控制器类:
public class Owner:Controller
{
private readonly IComRepository repository;
private readonly DbContext context;
public Owner(IComRepository repository, DbContext context)
{
this.repository=repository;
this.context=context;
}
[HttpGet("GetAllTypes")]
public async Task<IActionResult> GetAllTypes()
{
var ownerTypes=repository.GetTypes();
return Ok(ownerTypes);
}
}
我的存储库类
public Interface IComRepository
{
IList<Type> GetTypes();
}
public Class ComRepository : IComRepository
{
private readonly DbContext context;
public ComRepository(DbContext context)
{
this.context=context;
}
public IList<Type> GetTypes()
{
var allTypes= context.Types.ToList();
return allTypes;
}
}
现在我需要在我的控制器类中测试 GetAllTypes 方法。下面提到了我的测试类:
using moq;
[TestClass]
public Class OwnerTest
{
public OwnerTest()
{
var mockIcomrepo = new Mock<IComRepository>();
var mockDbcontext = new Mock<Dbcontext>();
OwnerController owner = new OwnerController(mockDbContext.object,mockIcomrepo.object);
}
[TestMethod]
public void GetTypes()
{
var allTypes= owner.GetAllTypes(); //It's not trigger to my controller
Assert.AreEqual(5,allTypes.count());
}
}
我该怎么做?任何人都知道这个问题的答案。
【问题讨论】:
-
模拟仓库没有设置做任何事情,所以默认情况下它会返回 null。
-
参考Moq Quickstart以更好地了解如何使用起订量
-
如果答案解决了你的问题,你能把它标记为答案
标签: c# unit-testing mocking moq