Automatically testing property getters/setters - c#

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

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:)

Apart from using auto properties I would think of using reflection to test out my models.. .
Just write a generic method that gets all the properties of your class and then use methods like these:
/ get value of property: public double Number
double value = (double)numberPropertyInfo.GetValue(calcInstance, null);
[C#]
// set value of property: public double Number
numberPropertyInfo.SetValue(calcInstance, 10.0, null);
For your example:
void Main()
{
const int testValue=5;
var test = (Test)Activator.CreateInstance(typeof(Test));
PropertyInfo valuePropertyInfo = typeof(Test).GetProperty("Value");
valuePropertyInfo.SetValue(test, testValue, null);
int value = (int)valuePropertyInfo.GetValue(test, null);
Console.Write(value); //Assert here instead
}
public class Test
{
private int _value;
public int Value {get {return _value;} set{_value=Value;}}
}
the output of the above function is 0 instead of a 5 which is expected. asserting here would have thrown an error.
What do you think about this approach.

Gallio/MbUnit has a contract verifier which does exactly what you are looking for. A typical usage of AccessContract is the following:
public class Foo // Dummy reference type.
{
private readonly int value;
public int Value { get { return value; } }
public Foo (int value)
{
this.value = value;
}
}
public class Bar
{
private Foo foo;
public Bar(string unusedParameter) { }
public Foo Foo // A complex property to be tested!
{
get { return foo; }
set
{
if (value == null)
throw new ArgumentNullException("value");
if (value.Value < 0)
throw new ArgumentOutOfRangeException();
if (value.Value == 666)
throw new ArgumentException("Inferno value strictly forbidden.");
foo = value;
}
}
}
And the test fixture which uses AccessorContract to run various tests on the property.
[TestFixture]
public class BarTest
{
[VerifyContract]
public readonly IContract AccessorTests = new AccessorContract<Bar, Foo>
{
Getter = target => target.Foo,
Setter = (target, value) => target.Foo = value,
ValidValues = { new Foo(123), new Foo(456), new Foo(789) },
AcceptNullValue = false,
DefaultInstance = () => new Bar("Hello"),
InvalidValues =
{
{ typeof(ArgumentOutOfRangeException), new Foo(-123), new Foo(-456) },
{ typeof(ArgumentException), new Foo(666) }
}
};
}
The contract verifier generates the following unit tests:
Have a look at the MbUnit test project for more usage examples.

Related

HasChanged method for c# model

I am searching for a solution where i can ask a model if a property has changed. But i want to prevent to write own setter methods for all models and all their properties.
I want to use this to automatically generate a update queries based models and there changed properties. But if my model has a boolean property Test which is by default false, then i can't differentiate if the value is from the request payload or if it is the default value.
I already saw the INotifyPropertyChanged Implementation but there i have to write a setter for all properties too.
public class Main
{
public static void main()
{
var person = new Person();
Console.WriteLine(person.HasChanged("Firstname")); // false
Console.WriteLine(person.HasChanged("Lastname")); // false
Console.WriteLine(person.HasChanged("LikesChocolate")); // false
person.Firstname = "HisFirstname";
person.LikesChocolate = true;
Console.WriteLine(person.HasChanged("Firstname")); // true
Console.WriteLine(person.HasChanged("Lastname")); // false
Console.WriteLine(person.HasChanged("LikesChocolate")); // true
}
}
public class Person : BaseModel
{
public string Firstname { get; set; }
public string Lastname { get; set; }
public bool LikesChocolate { get; set; }
}
public class BaseModel
{
public bool HasChanged(string propertyName)
{
// ...
}
}
I'd probably reuse the idea from WPF with their INotifyPropertyChanged pattern and simplify it a bit for the current needs. However, it resolves the question only partially, as you still need to write setters. But at least, you don't need to manage each property on its own.
So, the solution will be something like this:
void Main()
{
var person = new Person();
Console.WriteLine(person.HasChanged(nameof(Person.FirstName))); // false
Console.WriteLine(person.HasChanged(nameof(Person.LastName))); // false
Console.WriteLine(person.HasChanged(nameof(Person.LikesChocolate))); // false
person.FirstName = "HisFirstname";
person.LikesChocolate = true;
Console.WriteLine(person.HasChanged(nameof(Person.FirstName))); // true
Console.WriteLine(person.HasChanged(nameof(Person.LastName))); // false
Console.WriteLine(person.HasChanged(nameof(Person.LikesChocolate))); // true
}
public class Person : ChangeTrackable
{
private string _firstName;
private string _lastName;
private bool _likesChocolate;
public string FirstName
{
get { return _firstName; }
set { SetProperty(ref _firstName, value); }
}
public string LastName
{
get { return _lastName; }
set { SetProperty(ref _lastName, value); }
}
public bool LikesChocolate
{
get { return _likesChocolate; }
set { SetProperty(ref _likesChocolate, value); }
}
}
public class ChangeTrackable
{
private ConcurrentDictionary<string, bool> _changes =
new ConcurrentDictionary<string, bool>();
public bool HasChanged(string propertyName)
{
return _changes.TryGetValue(propertyName, out var isChanged)
? isChanged : false;
}
public void ResetChanges()
{
_changes.Clear();
}
protected void SetProperty<T>(
ref T storage, T value, [CallerMemberName] string propertyName = "")
{
if (!Equals(storage, value))
{
_changes[propertyName] = true;
}
}
}
The ChangeTrackable tracks if property was changed and does it without any reflection that guarantees high performance. Note, that with this implementation you need to call ResetChanges if you initialize property with some actual values after constructing the object. Drawback is that you need to write each property with its backing field and call SetProperty. On the other side, you decide what to track, that could be handy in the future in your application. Also we don't need to write property as strings (thanks to compile-time CallerMemberName and nameof) that simplifies refactorings.
INotifyPropertyChanged is the established practice for this type of requirement. Part of keeping your code maintainable is by keeping it predictable and by adopting best practices and patterns.
An alternative, which I wouldn't recommend, would be to use reflection to iterate over all of your properties and dynamically add a property changed event handler. This handler could then set a boolean flag which can be returned by your HasChanges method. Please refer to this for a staring point: AddEventHandler using reflection
I would recommend avoiding unnecessary complexity though and stick with PropertyChanged notifications in your setters.
As followup for my comment a proof of concept (online):
using System.Reflection;
public class HasChangedBase
{
private class PropertyState
{
public PropertyInfo Property {get;set;}
public Object Value {get;set;}
}
private Dictionary<string, PropertyState> propertyStore;
public void SaveState()
{
propertyStore = this
.GetType()
.GetProperties()
.ToDictionary(p=>p.Name, p=>new PropertyState{Property = p, Value = p.GetValue(this)});
}
public bool HasChanged(string propertyName)
{
return propertyStore != null
&& propertyStore.ContainsKey(propertyName)
&& propertyStore[propertyName].Value != propertyStore[propertyName].Property.GetValue(this);
}
}
public class POCO : HasChangedBase
{
public string Prop1 {get;set;}
public string Prop2 {get;set;}
}
var poco = new POCO();
poco.Prop1 = "a";
poco.Prop2 = "B";
poco.SaveState();
poco.Prop2 = "b";
poco.HasChanged("Prop1");
poco.HasChanged("Prop2");
Be aware, that reflection may reduce the performance of your application when used extensively.

Too many calculated properties in my class

I have class which have too many related calculated properties.
I have currently kept all properties are read only.
some properties need long calculation and it is called again when its related properties are needed.
How can create this complex object .Also i want these properties should not be set from external code. I need show hide as i am binding properties for UI. Also i think order is also important.
My Class is something like
public string A
{
get
{
return complexMethod();
;
}
}
public string B
{
get
{
if (A == "value")
return "A";
else return "B";
;
}
}
public bool ShowHideA
{
get
{
return string.IsNullOrEmpty(A);
;
}
}
public bool ShowHideB
{
get
{
return string.IsNullOrEmpty(B);
;
}
}
public string complexMethod()
{
string value = "";
// calculation goes here
return value;
}
}
Thanks
You need to use Lazy type provided by .net:
Lazy<YourType> lazy = new Lazy<YourType>();
Make your properties internal to not be set from external code.
Well tall order isn't it?
One of the coolest things about extension methods is you can use types. This is perfect for writing external programs to calculate property values. Start like this...
public static class XMLibrary
{
public static MC CalculateValues(this MC myclass)
{
//for each property calculate the values here
if (myclass.Name == string.Empty) myclass.Name = "You must supply a name";
if (myclass.Next == 0) myclass.Next = 1;
//when done return the type
return myclass;
}
}
public class MC
{
public string Name { get; set; }
public int Next { get; set; }
}
public class SomeMainClass
{
public SomeMainClass()
{
var mc = new MC { Name = "test", Next = 0 };
var results = mc.CalculateValues();
}
}
There are many other ways to do class validation on a model, for example dataannotations comes to mind, or IValidatableObject works too. Keeping the validation separate from the class is a good idea.
//Complex properites are simple
public class MyComplextClass{
public List<MyThings> MyThings {get;set;}
public List<FileInfo> MyFiles {get;set;}
public List<DateTime> MyDates {get;set;}
}

How to share all the properties of two interfaces with the same properties

I have two interfaces and the both have the same exact properties.
Just in case you're wondering why I've got two interfaces like these it's a long story, but yes, it has to be this way.
Based on a condition a List is returned if condition is the other way a List will be returned.
By looking at my interfaces and my code below I need to be able to make use of one object, in other words if doesn't matter which interface is returned I need to be able to work with one object and not looping one List interface and setting properties of the other.
I need something like this
compParts = genCompParts;
--- Code usage
public class ComponentParts : IComponentParts
{
public ComponentParts() { }
public ComponentParts(Guid userID, int compID, bool isGeneric)
{
List<IComponentPart> compParts = null;
List<IComponentPart_Max> genCompParts = null;
if (isGeneric)
{
genCompParts = GenericCatalogBL.GenericCatalogManagerBL.GetComponentPartsMax(compID);
}
else
{
compParts = CatalogManagerDL.GetComponentParts(userID, compID);
}
var verParts = compParts.Where(x => x.CompTypeName.ToLower().Contains("vertical"));
if (verParts.Count() > 0) { this.Vertical = verParts.ToList<IComponentPart>(); }
var horParts = compParts.Where(x => x.CompTypeName.ToLower().Contains("horizontal"));
if (horParts.Count() > 0) { this.Horizontal = horParts.ToList<IComponentPart>(); }
//... redundant code omitted
---Interface Snapshots---
I ended up creating a class library call Interfaces and I just share those interfaces across different programs in my solution.
It's what I should of done in the first place, just being lazy.
The totally brute-force way, assuming you don't own either IComponentPart or IComponentPart_Max and can't fix one of them.
Make a new interface that you control
interface IComponentPart {
string BrandGroup {get; set;}
int BrandID {get; set;}
// ...
}
Make wrappers for both of the existing interfaces that adapt them to your interface
class IComponentPartWrapper : IComponentPart {
private readonly CatelogDL.IComponentPart _underlyingPart;
public IComponentPartWrapper(CatelogDL.IComponentPart underlyingPart) {
_underlyingPart = underlyingPart
}
public string BrandGroup {
get {return _underlyingPart.BrandGroup;}
set {_underlyingPart.BrandGroup = value;}
}
public int BrandID {
get {return _underlyingPart.BrandID ;}
set {_underlyingPart.BrandID = value;}
}
// ...
}
class IComponentPart_MaxWrapper : IComponentPart {
private readonly GenericCatalogDL.IComponentPart_Max _underlyingPart;
public IComponentPartWrapper(GenericCatalogDL.IComponentPart_Max underlyingPart) {
_underlyingPart = underlyingPart
}
public string BrandGroup {
get {return _underlyingPart.BrandGroup;}
set {_underlyingPart.BrandGroup = value;}
}
public int BrandID {
get {return _underlyingPart.BrandID ;}
set {_underlyingPart.BrandID = value;}
}
// ...
}
Make your code use your interface, and wrap the results from either library in the corresponding wrapper
public class ComponentParts : IComponentParts
{
public ComponentParts() { }
public ComponentParts(Guid userID, int compID, bool isGeneric)
{
List<IComponentPart> compParts;
if (isGeneric)
{
compParts = GenericCatalogBL.GenericCatalogManagerBL.GetComponentPartsMax(compID)
.Select(x => new IComponentPart_MaxWrapper(x))
.ToList();
}
else
{
compParts = CatalogManagerDL.GetComponentParts(userID, compID)
.Select(x => new IComponentPartWrapper(x))
.ToList();
}
// ...

C# Properties based on choice

I need a little help i am using a class and want to set the properties based on choice on type int,string and datetime here is my code that i wrote but as my constructor will be confused between public string paramValue and public int? paramValue what is the best way to set properties based on choice so only one property can be set a time.Thanks for any suggestion
public class PassData
{
private string _ParamName { get; set; }
private int? _ParamValueInt { get; set; }
private string _ParamValueString { get; set; }
private DateTime? _ParamValueDateTime { get; set; }
public string paramName
{
get { return _ParamName; }
set { _ParamName = value;}
}
public string paramValue
{
get { return _ParamValueString; }
set {_ParamValueString = value; }
}
public int? paramValue
{
get { return _ParamValueInt; }
set { _ParamValueInt = value; }
}
public PassData(string ParamName, int ParamValue)
{
paramName = ParamName;
paramValue = ParamValue;
}
public PassData(string ParamName, string ParamValue)
{
ParamName = ParamName;
ParamValueString = ParamValue;
}
public PassData(string ParamName, DateTime ParamValue)
{
ParamName = ParamName;
ParamValueDateTime = ParamValue;
}
}
Basically, you can't have multiple properties on an object that only differ by type. You have a few options.
1) Create a single property that can hold various types:
private Object _paramValue;
public Object ParamValue
{
get { return _paramValue; }
set {_paramValue= value; }
}
In your setter, you can throw an exception if the value is a type you don't like. You'd also have to upcast the result every time you called the getter, making this solution not ideal. If you want to go this route, I'd suggest making the property an interface, and defining various implementations for the types of data you need.
2) Create a generic class:
public class PassData<T>
{
private T _paramValue;
public T paramValue
{
get { return _paramValue; }
set {_paramValue= value; }
}
}
This has the disadvantage of not being able to change the type after the instance is created. It was unclear if this was a requirement for you.
I like this design as it provides for the possibility of making the constructor for this class private:
public class PassData<T>
{
private PassData(T value)
{
this._paramValue = value;
}
}
If you did this, you can create overloaded static methods to allow the creation of instances:
public static PassData<String> CreateValue(string value)
{
return new PassData<String>(value);
}
public static PassData<Int32> CreateValue(Int32 value)
{
return new PassData<Int32>(value);
}
That way, you can control what types can be created.
Not an answer (in the sense that it does not offer you a way to do what you're trying to do, as Mike Christensen's answer covers it). I just wanted to get more into why what you are trying to do is not working.
Your expectation for it to work is not unreasonable per se, the issue is that c# is not polymorphic on return values. I think some other languages are, C# is not.
i.e. while in c#, you can do:
public void test(int val) {}
public void test(string val) {}
// When you call `test` with either an int or a string,
// the compiler will know which one to call
you CAN'T do:
public int test() {return 1;}
public string test() {return "1";}
// does not compile. The compiler should look at the call
// site and see what you assign the result of "test()" to
// to decide. But there are various edge cases and it was decided
// to leave this out of the language
Now, the get on string paramValue is functionally equivalent to this scenario. You're trying to get the compiler to decide which paramValue to call based on the return value.

Design a mutable class that after it's consumed becomes immutable

Suppose that the scenario doesn't allow to implement an immutable type. Following that assumption, I'd like opinions / examples on how to properly design a type that after it's consumed, becomes immutable.
public class ObjectAConfig {
private int _valueB;
private string _valueA;
internal bool Consumed { get; set; }
public int ValueB {
get { return _valueB; }
set
{
if (Consumed) throw new InvalidOperationException();
_valueB = value;
}
}
public string ValueA {
get { return _valueA; }
set
{
if (Consumed) throw new InvalidOperationException();
_valueA = value;
}
}
}
When ObjectA consumes ObjectAConfig:
public ObjectA {
public ObjectA(ObjectAConfig config) {
_config = config;
_config.Consumed = true;
}
}
I'm not satisfied that this simply works, I'd like to know if there's a better pattern (excluded, as said, making ObjectAConfig immutable by design from begin).
For example:
can make sense define a monad like Once<T> that allow the wrapped value to be initialized only once?
can make sense define a type that returns the type itself changing a private field?
What you are implementing sometimes goes under the name "popsicle immutability" - i.e. you can freeze it. Your current approach will work - indeed I use that pattern myself in numerous places.
You can probably reduce some duplication via something like:
private void SetField<T>(ref T field, T value) {
if (Consumed) throw new InvalidOperationException();
field = value;
}
public int ValueB {
get { return _valueB; }
set { SetField(ref _valueB, value); }
}
public string ValueA {
get { return _valueA; }
set { SetField(ref _valueA, value); }
}
There is another related approach, though: a builder. For example, taking your existing class:
public interface IConfig
{
string ValueA { get; }
int ValueB { get; }
}
public class ObjectAConfig : IConfig
{
private class ImmutableConfig : IConfig {
private readonly string valueA;
private readonly int valueB;
public ImmutableConfig(string valueA, int valueB)
{
this.valueA = valueA;
this.valueB = valueB;
}
}
public IConfig Build()
{
return new ImmutableConfig(ValueA, ValueB);
}
... snip: implementation of ObjectAConfig
}
Here there is a truly immutable implementation of IConfig, and your original implementation. If you want the frozen version, call Build().

Categories

Resources