How do I check “no exception occurred” in my MSTest unit test?

后端 未结 6 2009
再見小時候
再見小時候 2020-12-30 18:34

I\'m writing a unit test for this one method which returns \"void\". I would like to have one case that the test passes when there is no exception thrown. How do I write t

6条回答
  •  心在旅途
    2020-12-30 18:40

    This helper class scratched my itch with MSTest. Maybe it can scratch yours also.

    [TestMethod]
    public void ScheduleItsIneligibilityJob_HasValid_CronSchedule()
    {
        // Arrange
        var factory = new StdSchedulerFactory();
        IScheduler scheduler = factory.GetScheduler();
    
        // Assert
        AssertEx.NoExceptionThrown(() =>
            // Act
            _service.ScheduleJob(scheduler)
        );
    }
    
    public sealed class AssertEx
    {
        public static void NoExceptionThrown(Action a) where T:Exception
        {
            try
            {
                a();
            }
            catch (T)
            {
                Assert.Fail("Expected no {0} to be thrown", typeof(T).Name);
            }
        }
    }
    

提交回复
热议问题