類型我想測試一下下面的代碼:如何使用一個模擬當代碼驗證它接收
public IEnumerable<KeyValuePair<Fact, Exception>> ValidateAll()
{
//...do something
var invalidFacts = GetInvalidFacts();
//...do something
return duplicateFacts.Concat(invalidFacts);
}
private IEnumerable<KeyValuePair<Fact, Exception>> GetInvalidFacts()
{
var invalidFacts = Facts.Select(fact =>
{
try
{
fact.Validate();
return new KeyValuePair<Fact, Exception>(fact, null);
}
catch (FormatException e)
{
return new KeyValuePair<Fact, Exception>(fact, e);
}
catch (Exception e)
{
return new KeyValuePair<Fact, Exception>(fact, e);
}
}).Where(kv => kv.Value != null).ToList();
return invalidFacts;
}
基本上測試的目的是檢查是否存在「事實」之內的所有對象的IEnumerable將調用其Validate方法。由於我不想測試這些對象中的代碼,因此已經有很多測試能夠做到這一點,我想注入一個假事實列表。我正在使用起訂量來製作假貨。
所以我的單元測試是這樣的:
[TestMethod]
public void ValidateAll_ValidateMethodIsInvokedOnAllFacts_WhenCalled()
{
var anyFactOne = new Mock<Fact>(); //Fact is an abstract class.
anyFactOne.Setup(f => f.Validate());
var dataWarehouseFacts = new DataWarehouseFacts { Facts = new Fact[] { anyFactOne.Object, FactGenerationHelper.GenerateRandomFact<SourceDetails>() } };
dataWarehouseFacts.ValidateAll();
}
現在,我發現了一個異常,因爲代碼實際上是驗證一種可以注射到DataWarehouseFacts類,像這樣的事實:
public IEnumerable<Fact> Facts
{
get
{
.....
}
set
{
var allowedTypes = new []
{
typeof(ProductUnitFact),
typeof(FailureFact),
typeof(DefectFact),
typeof(ProcessRunFact),
typeof(CustomerFact),
typeof(ProductUnitReturnFact),
typeof(ShipmentFact),
typeof(EventFact),
typeof(ComponentUnitFact),
typeof(SourceDetails)
};
if(!value.All(rootFact => allowedTypes.Contains(rootFact.GetType())))
throw new Exception ("DataWarehouseFacts can only be set with root facts");
ProductUnitFacts = value.OfType<ProductUnitFact>().ToList();
FailureFacts = value.OfType<FailureFact>().ToList();
DefectFacts = value.OfType<DefectFact>().ToList();
ProcessRunFacts = value.OfType<ProcessRunFact>().ToList();
CustomerFacts = value.OfType<CustomerFact>().ToList();
ProductUnitReturnFacts = value.OfType<ProductUnitReturnFact>().ToList();
ShipmentFacts = value.OfType<ShipmentFact>().ToList();
EventFacts = value.OfType<EventFact>().ToList();
ComponentUnitFacts = value.OfType<ComponentUnitFact>().ToList();
SourceDetails = value.OfType<SourceDetails>().Single();
}
}
什麼是避開此驗證的最佳方法?
謝謝。