3

We are using NBuilder for generating test data for our tests. We have a few models with private setters. So setting thos properties is only possible throughout the constructor. The problem is that we get the following error from NBuilder:

CompanyAddressViewModel does not have a default parameterless constructor

I understand the error. Do I really need to create a default constructor in my class?

Here is my NBuilder code:

Builder<CompanyAddressViewModel>.CreateNew().Build()
Cœur
  • 37,241
  • 25
  • 195
  • 267
DAG
  • 2,460
  • 5
  • 33
  • 61
  • 1
    Same issue. For example Newtonsoft.Json is able to instantiate classes without default constructors. This feature would be really helpful in NBuilder too. – neleus Apr 19 '17 at 13:19

3 Answers3

3

You can use WithConstructor() or WithFactory() method, in Net Core 2.1 WithConstructor() method is deprecated.

Builder<CompanyAddressViewModel>.CreateNew(). WithFactory (() => new parameter()).Build()

1

Former versions uses WithConstructor() method, but it's obsolete in these days, so you should use WithFactory() method:

Builder<CompanyAddressViewModel>
         .CreateNew()
         .WithFactory(() => new CompanyAddressViewModel("your", "parameter"))
         .Build()
1_bug
  • 5,505
  • 4
  • 50
  • 58
0

You need to use With method.

Builder<CompanyAddressViewModel>
               .CreateNew()
               .With(() => new CompanyAddressViewModel(...))
               .Build()