title: Unit testing FluentValidation rules for classes with sub/child classes
body: <p>Is it possible to write unit tests for fluentvalidation classes when the object we are validating has child classes that are also being validated. </p>
  
  <p>As an example:
  My class looks like this</p>
  
  <pre><code>public class TestModel
  {
  
      public class SubData
      {
          public int SubDataVal { get; set; }
      }
  
      public int ParentVal { get; set; }
      public SubData Sub { get; set; }
  
  }
  </code></pre>
  
  <p>My validation logic looks like this:</p>
  
  <pre><code>public class TestModelValidator : AbstractValidator&lt;TestModel&gt;
  {
      public TestModelValidator()
      {
          RuleFor(o =&gt; o.ParentVal).GreaterThan(0);
          RuleFor(o =&gt; o.Sub.SubDataVal).GreaterThan(0);
      }
  }
  </code></pre>
  
  <p>And when I write the following unit test </p>
  
  <pre><code>    [Test]
      public void Should_have_error_when_val_is_zero()
      {
          validator = new TestModelValidator();
          validator.ShouldHaveValidationErrorFor(model =&gt; model.ParentVal, 0);
      }
  </code></pre>
  
  <p>I get a "System.NullReferenceException : Object reference not set to an instance of an object." exception from
  <strong>FluentValidation.TestHelper.ValidatorTester`2.ValidateError(T instanceToValidate)</strong></p>
  
  <p>(if I remove the <em>RuleFor(o => o.Sub.SubDataVal).GreaterThan(0);</em> line, then it works!)</p>
  
  <p>Similarly if I try and unit test the actual child class with:</p>
  
  <pre><code>    [Test]
      public void Should_have_error_when_sub_dataVal_is_zero()
      {
          validator = new TestModelValidator();
          validator.ShouldHaveValidationErrorFor(model =&gt; model.Sub.SubDataVal, 0);
      }
  </code></pre>
  
  <p>I get a "System.Reflection.TargetException : Object does not match target type." from <strong>FluentValidation.TestHelper.ValidatorTester`2.ValidateError(T instanceToValidate)</strong> </p>