【发布时间】:2023-03-28 06:57:02
【问题描述】:
我有课
public class Restrictions
{
[Key]
public short RestrictionId { get; set; }
public string Description { get; set; }
public string BlockCode { get; set; }
public List<CustomerRestrictions> CustomerRestrictions { get; set; }
}
和
public class CustomerRestrictions
{
public int CustomerId { get; set; }
public CustomerContacts CustomerContacts { get; set; }
public string RestrictionId { get; set; }
public Restrictions Restrictions { get; set; }
}
然后
public class CustomerContacts
{
[Key]
public long CustomerId { get; set; }
public string Btn { get; set; }
public List<CustomerRestrictions> CustomerRestrictions { get; set; }
}
好像是多对多的关系。
现在我想对控制器进行单元测试。有一个类似的example. 但它没有多对多。
我的控制器是
[Route("api/[controller]")]
public class BtnRulesController : Controller
{
private readonly IBtnRulesRepository _btnRulesRepository;
public BtnRulesController(IBtnRulesRepository btnRulesRepository)
{
_btnRulesRepository = btnRulesRepository;
}
// GET api/BtnRules
[HttpGet]
public IList<Restrictions> Get()
{
return _btnRulesRepository.GetRestrictions();
}
目前困难的是如何在单元测试中创建样本数据。
public class SimpleBtnRulesControllerTest
{
[Fact]
public void GetAllBtnRules_Should_Return_All_BtnRules()
{
var repo = new Mock<IBtnRulesRepository>().Object;
var controller = new BtnRulesController(repo);
var testBtnRules = GetTestBtnRules();
var result = controller.Get();
Assert.Equal(testBtnRules.Count,result.Count);
}
public List<Restrictions> GetTestBtnRules()
{
var testBtnRules = new List<Restrictions>();
var testCustomerRestrictionsList = new List<CustomerRestrictions>();
var testCustomerRestrictions = new CustomerRestrictions();
testCustomerRestrictions.CustomerId = 1;
testCustomerRestrictions.RestrictionId = "1";
testCustomerRestrictions.Restrictions=new Restrictions();
testCustomerRestrictions.CustomerContacts=new CustomerContacts();
testCustomerRestrictionsList.Add(new CustomerRestrictions());
testBtnRules.Add(new Restrictions() {RestrictionId = 1, Description = "Demo1",BlockCode = "AdminBlock1",testCustomerRestrictionsList});
testBtnRules.Add(new Restrictions() { RestrictionId = 2, Description = "Demo2", BlockCode = "AdminBlock2" ,testCustomerRestrictionsList});
return testBtnRules;
}
但是我收到错误 CS0747 Invalid initializer member declarator。
【问题讨论】:
-
您错过了 CustomerRestrictions = testCustomerRestrictionsList。相反,您只需将 testCustomerRestrictionsList 传递给对象初始化程序。
-
没有你在哪里实际设置
IBtnRulesRepository实际返回数据的地方。没有任何var mock = new Mock<IBtnRulesRepository>(); mock.Setup(x => x.GetRestrictions)... etc如果你希望它保持你编码的方式,那么你正在做一个集成测试...... -
@CallumLinington,好点子。但是在
Setup/Returns我仍然需要发送样本数据。所以我必须通过硬代码生成它们?
标签: c# unit-testing moq