Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically testing property getters/setters

We use backing fields for a lot of properties on our domain objects, for example:

protected string _firstname;

public virtual string Firstname
{
    get { return _firstname; }
    set { _firstname = value; }
}

I've occasionally made stupid typos like the example below, and would like to write a single test that verifies all these properties, rather than manually doing a test per object.

public virtual string Firstname
{
    get { return _firstname; }
    set { _firstname = Firstname; }
}

Would it be easy to write or does a library already exist to test these backing fields get/set correctly? This would only run on properties with setters and (presumably) a backing field that matches the property name using camel-case underscore

like image 818
Chris S Avatar asked Feb 23 '23 05:02

Chris S


1 Answers

Another solution would be to use automatic properties to eliminate this problem:

public virtual string FirstName { get; set; }

UPDATE (see comments, backing field seems needed): Another possibility is to generate the pocos. Simple t4-template 'Person.tt'

<#@ template language="C#" #>
<# var pocos = new [] {
    Tuple.Create("FirstName", "string"), 
    Tuple.Create("LastName", "string"), 
    Tuple.Create("Age", "int")}; #>
public partial class Person {
    <# foreach(var t in pocos) {#>

    protected <#= t.Item2#> _<#= t.Item1.ToLowerInvariant()#>;
    public virtual <#= t.Item2#> <#= t.Item1#>
    {
        get { return _<#= t.Item1.ToLowerInvariant()#>; }
        set { _<#= t.Item1.ToLowerInvariant()#> = value; }
    }
    <#}#>
}

Now this could of course bring with it as many problems as it solves but it may be worth looking at ... maybe:)

like image 110
alun Avatar answered Mar 05 '23 09:03

alun