带有catch的catch语句中的单元测试代码

时间:2018-06-21 09:07:55

标签: c# unit-testing error-handling try-catch throws

有没有一种方法可以在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);
        }

2 个答案:

答案 0 :(得分:2)

不,您无法跳过catch的throw语句。但是,您可以在单元测试方法上附加ExpectedExceptionAttribute,以指示在执行测试方法期间可能会出现异常。您可以在here阅读有关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);
    }

此外,我建议不要使用通用异常,而应定义具有特定异常的属性。

答案 1 :(得分:0)

还有另一种使用xunit中的Record.Exception进行此操作的方法,请参见链接下方的更多内容:

How to test for exceptions thrown using xUnit, SubSpec and FakeItEasy