Search code examples
c#testingnunitncover

How to write test case for protected method throwing exception?


i am working with visual studio and writing Nunit test cases. While Writing test cases i encountered a class which is having a protected method and that method so throwing an exception of "NotImplementedException" type. I tried to use Invoke key-word but Ncover is not cover that portion. I also tried to use try catch but my code reviewer is saying not to use try catch block in test cases. So, friend is there any other way to write test case for such type of issue. I am mentioning the class and test cases, please tell me how to solve it.

Class File:-

public class UpdateMacActivityPriorityTranslator : EntityMapperTranslator<object, CSUpdateMACActivityPriorityResponseType>
    {

        protected override CSUpdateMACActivityPriorityResponseType BusinessToService(IEntityTranslatorService service, object value)
        {
            throw new NotImplementedException();
        }
    }

Test case:-

public void BusinessToServiceTest()
        {
            var updateMacActivityPriorityTranslator = new UpdateMacActivityPriorityTranslator();
            var service = MockRepository.GenerateStub<IEntityTranslatorService>();
            var value = new object();
            var invokeProtectedBusinessToService = new                      PrivateObject(updateMacActivityPriorityTranslator,new PrivateType(                                                                       typeof(UpdateMacActivityPriorityTranslator)));
            NUnit.Framework.Assert.Throws<NotImplementedException>(
                () =>
                invokeProtectedBusinessToService.Invoke("BusinessToService",
                                                        new object[] { service, value }));
        }

Solution

  • If your class (fixture) containing the test method BusinessToServiceTest already derives from (has as base class) UpdateMacActivityPriorityTranslator, I guess you could just do:

    public void BusinessToServiceTest()
    {
        var updateMacActivityPriorityTranslator = new UpdateMacActivityPriorityTranslator();
        var service = MockRepository.GenerateStub<IEntityTranslatorService>();
        var value = new object();
        NUnit.Framework.Assert.Throws<NotImplementedException>(
            () => updateMacActivityPriorityTranslator.BusinessToService(service, value)
            );
    }
    

    or you could just use this instead of updateMacActivityPriorityTranslator, so:

    public void BusinessToServiceTest()
    {
        var service = MockRepository.GenerateStub<IEntityTranslatorService>();
        var value = new object();
        NUnit.Framework.Assert.Throws<NotImplementedException>(
            () => BusinessToService(service, value)
            );
    }