How to bypass base class method call in MSTest?

NewCodee 1 Reputation point
2021-09-30T10:33:25.587+00:00

I have the following code in c#:

public class MyChildClass : AbstractBaseClass
{
public void myMethod()
{
abstractBaseClassMethodCall();
if(condition)
........
}
}

I have to write a unit test for the above code using MSTest. Here, baseClassMethodCall() fails with error message, "System.NullReferenceException: Object reference not set to an instance of an object."
I cannot change anything in the base class as it is a predefined class with the protected constructor.

Is there a way to bypass the base class method call and continue testing the next line? Maybe by using mocks or shims?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,277 questions
Visual Studio Testing
Visual Studio Testing
Visual Studio: A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.Testing: The act or process of applying tests as a means of analysis or diagnosis.
329 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Viorel 112.5K Reputation points
    2021-09-30T10:57:30.617+00:00

    Maybe you can use a parameter:

    public void myMethod( bool isTesting = false )
    {
       if( ! isTesting) abstractBaseClassMethodCall();
       . . .
    }
    

    Or divide it, and test myMethod2 separately:

    public void myMethod( )
    {
       abstractBaseClassMethodCall();
       myMethod2( );
    }
    
    void myMethod2( )
    {
       . . .
    }
    

  2. Karen Payne MVP 35,036 Reputation points
    2021-10-01T09:31:08.547+00:00

    A debug session is in order as attempting test is no different from attempting to test something private. Any unit test that uses the abstract class is for testing functionality, not if the method will break somehow.

    0 comments No comments