RPM1984
RPM1984

Reputation: 73132

How to tell NBuilder to intercept getters when generating object?

I've got this NBuilder code:

var fakeReviews = Builder<Review>
   .CreateListOfSize(100)
   .Build()
   .ToList()
   .AsReadOnly();

Pretty dead simple.

But it's erroring here on this property on Review:

public bool WasWrittenByAdmin
{  
   get
   {
      if (User == null) throw new InvalidOperationException("Must load User.");
      return User.UserSettings != null && User.UserSettings.IsAdmin;
   }
}

Basically, i think NBuilder is trying to evaluate all the properties, including the getter, but that User property doesn't exist.

Even if i do this:

var fakeReviews = Builder<Review>
   .CreateListOfSize(100)
   .All().With(x => x.User = Builder<User>.CreateNew().Build())
   .Build()
   .ToList()
   .AsReadOnly();

It still errors.

Is there any way i can tell NBuilder to intercept that getter, or how do i setup the User property before it tried to evaluate it? (and hence prevent the error).

Upvotes: 2

Views: 1082

Answers (1)

dougajmcdonald
dougajmcdonald

Reputation: 20047

It's not ideal, but I got round this by explicitly setting values of the properties I didn't want.

In your case, that would mean either returning the true/false depending on what you were testing for, or throwing the exception.

So basically you'd make perhaps two methods like this:

public static Review BuildReviewByAdmin() 
{
    return Builder<Review>.CreateNew().With(x => x.WasWrittenByAdmin = true).Build();
}

public static Review BuildReviewByNonAdmin() 
{
    return Builder<Review>.CreateNew().With(x => x.WasWrittenByAdmin = false).Build();
}

Then you could use the one you wanted in specific tests.

If however you're looking to test the logic of the getting I'd do that differently.

Additionally there is an NBuiler google code issue which touches on this issue:

https://code.google.com/p/nbuilder/issues/detail?id=79

Upvotes: 0

Related Questions