chevron-thin-right chevron-thin-left brand cancel-circle search youtube-icon google-plus-icon linkedin-icon facebook-icon twitter-icon toolbox download check linkedin phone twitter-old google-plus facebook profile-male chat calendar profile-male
Welcome to Typemock Community! Here you can ask and receive answers from other community members. If you liked or disliked an answer or thread: react with an up- or downvote.
0 votes
Having an example:

  public class Base
  {
    public Base()
    { }
    public string NullError
    {
      get{ return nullError;}
    }
    private readonly string nullError = "Error";
  }
  public class Derived : Base
  {
    public Derived()
      : base()
    {
      NullError.ToString(); //NullReference Exception Here
    }
  }
  [TestClass()]
  public class TableColumnTest
  {
    [TestMethod]
    public void TestBaseInitializations()
    {
      Mock mock = MockManager.Mock(typeof(Derived),  Constructor.NotMocked);
      mock.ExpectUnmockedConstructor();
      mock.CallBase.ExpectConstructor();
      new Derived();
      mock.Verify();
    }
  }

I've got a NullReferenceException. It seems that readonly fields on base class are not initalized properly or is it my mistake?
asked by ppr (600 points)

2 Answers

0 votes
Hi
You are getting the Exception because the Base constructor was not called.
You can use use ExpectUnmockedConstructor for the base type or mock
the property NullError.
It all depends on what you need to do in the test.

//Call base constructor
[Test]
public void TestBaseInitializations()
{
   Mock mock = MockManager.Mock(typeof(Derived), Constructor.NotMocked);
   mock.ExpectUnmockedConstructor();
   mock.CallBase.ExpectUnmockedConstructor();
   new Derived();
   mock.Verify();
}

//Mock NullError property
[Test]
public void TestBaseInitializations()
{
   Mock mock = MockManager.Mock(typeof(Derived), Constructor.NotMocked);
   mock.ExpectUnmockedConstructor();
   mock.CallBase.ExpectGet("NullError", "abc");
   new Derived();
   mock.Verify();
}
answered by ohad (35.5k points)
0 votes
Perhaps I can give a more detailed explaination.

Initializing instance fields e.g:
private readonly string nullError = "Error";
is actually done when the constructor is called.
something like:
public Base()
{ 
   // Hidden code
   nullError = "Error";
}


So if the constuctor is mocked, the field never gets initialized.

:idea: If you want more control over the fields, (e.g. when you want to mock the constructor but set the field), you can use the new Mocking Fields APIs (since version 4.2.2) to reset the field.
answered by eli (5.1k points)
...