[英]Unit test code in catch statement with a throw
有没有一种方法可以在catch语句中测试代码,诀窍是catch以throw
结束,这就是事情的发展方向。 所以问题是,是否有一种方法可以避免在运行我的Test方法时抛出该异常,或者可以在我的测试中使其适应?
下面的方法只是简单地更新值,并在捕获时throw
public void UpdateCase(LinqToSQLModelName record, IProgress<string> statusReporter)
{
try
{
statusReporter.Report(record.Reference);
_service.PushToService(record);
record.ProcessedDate = DateTime.Now;
record.StatusId = (int)Status.Processed;
}
catch (Exception ex)
{
record.StatusId = (int)Status.Fail;
record.ErrorExceptions = ex.StackTrace;
record.ProcessedDate = DateTime.Now;
Result = false;
throw ex;//How do dodge this when running my test/ Accomodate it on my Test
}
finally
{
_db.SubmitChanges();
}
}
我需要现在测试捕获部分,在下面进行测试
[TestMethod()]
public void UpdateCaseErrorTest()
{
var repository = new Mock<IDataContext>();
var errorLoggerRepository = new Mock<IExceptionLogger>();
var serviceRepository = new Mock<IServiceInterface>();
repository.Setup(m => m.Get()).Returns(new
ManualWithDrawDataContext());
repository.Setup(m => m.GetCouncilRefundRecord())
.Returns(new LinqToSQLModelName
{
refrence= "10",
Reason = "Reason",
DateCaptured = DateTime.Now,
});
var sut = new DataContext(repository.Object.Get(), serviceRepository.Object, errorLoggerRepository.Object);
sut.UpdateCase(repository.Object.GetCouncilRefundRecord(), null);//This null allows me to go to the catch
Assert.IsFalse(sut.Result);
}
不,您无法跳过catch的throw语句。 但是,您可以将ExpectedExceptionAttribute
附加到单元测试方法上,以便表明在执行测试方法期间应预期有异常。 您可以在此处阅读有关ExpectedExceptionAttribute
的信息 。
[TestMethod()]
[ExpectedException(typeof(Exception))]
public void UpdateCaseErrorTest()
{
var repository = new Mock<IDataContext>();
var errorLoggerRepository = new Mock<IExceptionLogger>();
var serviceRepository = new Mock<IServiceInterface>();
repository.Setup(m => m.Get()).Returns(new
ManualWithDrawDataContext());
repository.Setup(m => m.GetCouncilRefundRecord())
.Returns(new LinqToSQLModelName
{
refrence= "10",
Reason = "Reason",
DateCaptured = DateTime.Now,
});
var sut = new DataContext(repository.Object.Get(), serviceRepository.Object, errorLoggerRepository.Object);
sut.UpdateCase(repository.Object.GetCouncilRefundRecord(), null);//This null allows me to go to the catch
Assert.IsFalse(sut.Result);
}
另外,我建议不要捕获一般异常,而应定义具有特定异常的属性。
还有一种使用xunit中的Record.Exception进行此操作的方法,请参见链接下方的更多信息:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.