pmrogala / Buildenator

A test data builders source generator for .net 5 and later.
MIT License
19 stars 1 forks source link

Add a partial method to generated builder class for post build steps #42

Closed powerdude closed 2 years ago

powerdude commented 2 years ago

It would be great if the generated builder class included something like the following:

partial void PostBuild(<<type>> buildResult);

the developer could then implement this method to do additional work to the result before it is returned. The Build method would need to call this before it returns a result.

pmrogala commented 2 years ago

It cannot be a partial method if it's going to be used in the Build method, because it would enforce implementation in all builders.

What I can do is just detecting if someone wrote his own implementation of the PostBuild method, if yes, then I will remove the default implementation of it. (The same as it work now with the "with" methods)

powerdude commented 2 years ago

that's not really true. You can include the call to PostBuild and if the developer provides an implementation, it will be used. If not, the compiler will provide a no-op implementation or just remove the call. I've used this technique many times. You can try this class:


public class Model
{
    public int Id {get;set;}
}
public partial class Tester
{
     partial void PostBuild( Model item);

    public object Build()
    {
          var item = new Model{Id=1};
          PostBuild(item);

         return item;
    }
}

/*  the class above will compile.  Uncomment this block and it'll still compile.
public partial class Tester
{
     partial void PostBuild(Model item)
    {
    item.Id = 2;
       Console.Writeline( "here");
    }  
}
*/
pmrogala commented 2 years ago

Yeah, I know how it works. However, when I try to generate the partial method, all the integration tests fails for all other builders, saying that there's no implementation of the partial method...

Anyway, I would like to still keep the netstandard 2.0 backward compatibility, so I will go with what I wrote. From the end user perspective there is no difference at all.

pmrogala commented 2 years ago

44