mardi 28 mars 2017

Assert specific constructor called by child class

I am trying to write a test to verify that child classes call a specific base class' constructor. Effectively, IDs for my entities are generated when the object is instantiated by the server. I am using NHibernate as my ORM, and so I need a 0-parameter constructor. I would prefer that this constructor not generate a Guid everytime that NHibernate hydrates an entity, so I created a second constructor for my base entity with a Guid as a paramter.

It looks something like this

public abstract class EntityBase {
    public Guid ID {get; protected set;}

    protected EntityBase() { }

    public EntityBase(Guid id) { ID = id }

    public static Guid NewID => GenerateGuid();
}

public class Entity : EntityBase {
    public int X {get; set;}

    protected Entity() { }

    public Entity(int x) : base(NewID) { X = x; }
}

This test I want to write should assert that all constructors (except the 0-parameter constructor) of all concrete child classes of EntityBase call the correct base constructor:

public EntityBase(Guid id) { ID = id }

Currently, my code loops through constructors on all concrete classes assignable from EntityBase, but I don't know how to make the final check. Research into solutions suggested attempting to read IL using reflection. I considered trying to check if 'NewID' had been called, but was unable to find any accomplish that either.

Is there a way to achieve this, or is my solution to the NHibernate problem the real issue?





Aucun commentaire:

Enregistrer un commentaire