I have a class like this:
public class MyClass
{
private MyStruct _someProperty;
public MyStruct SomeProperty
{
set
{
if(StructureChanged(_someProperty, value))
{
_someProperty = value;
OnSomePropertyChanged();
}
}
}
private bool StructureChanged(MyStruct oldValue, MyStruct newValue)
{
// Check if any property of newValue is different from oldValue
// This is a check for semantic equality, not referential equality
}
internal protected virtual OnSomePropertyChanged()
{
// ...
}
}
And a test like this:
// Arrange
_myClass = MockRepository.GeneratePartialMock<MyClass>();
_myClass.SomeProperty = new MyStruct();
// Act
_myClass.SomeProperty = new MyStruct(); // This is semantically equal to the current value
// Assert
_myClass.AssertWasNotCalled(m => m.OnSomePropertyChanged());
Of course, the test fails because OnSomePropertyChanged is called when I set the property the first time. What I want is to set the property the first time, reset the AssertWasNotCalled value somehow, and then set the property again and make sure OnSomePropertyChanged is not called again. Is there any way to do this?
Actually, in that case this is expected that OnSomePropertyChanged() is called once. But not more and not less than once.
The suitable assert statement then might look like:
_myClass.AssertWasCalled(m => m.OnSomePropertyChanged(), opt => opt.Repeat.Once());
PS
Another test should be written which ensures OnSomePropertyCnahged() is triggered after SomeProperty is actually changed.
In that case in our test it is guaranteed OnSomePropertyCnahged() is triggered when SomeProperty was changed first time.
And expectation it is called once, but not two times, guarantees that event is not fired when that is not expected.
Related
What is the flow of the below code snippet?
What does return; means?
What will it do when return; executes?
public bool ActionSafeAction
{
get
{
return this.ActionSafeAction;
}
set
{
if (value.Equals(this.ActionSafeAction))
{
return;
}
if (value)
{
this.ActivateItem(this.ActionSafeAction);
this.ActionSASelected = false;
}
this.ActionSafeAction= value;
this.NotifyOfPropertyChange(() => this.ActionSafeAction);
}
}
It will do nothing more of what comes after the return. It immediately returns from the setter and doesn't change any underlying value.
Writing ActionSafeAction = true if ActionSafeAction is already true will hit this return statement and not do anything more.
Properties are little more then Syntax Sugar for Get and Set functions. That is what they are designed to be.
Set in paritcular is effectively a function that takes a parameter "value" and returns void. Except for the name and the way you call it, that set is effectively: public void SetActionSafeAction(bool value). Making getters and setters easily implement and useable - again, that is what Properties are there for.
The return in the if will end the execution of this function, there and then. As it would with any other function that returns void. The rest of the checks and the setting/change notification will not be executed.
I think if we illistruate the getter and setter like below you may understand better. Get and Set are implict definition of two seperated method that effect a particular member.
public class Foo
{
private string myMember;
public string GetMyMember()
{
return myMeber;
}
public void SetMyMember(string value)
{
myMember = value;
}
}
So as you see setter is a actually a void method and when you call return statement at any part of this method it will just leave method without executing rest of the code. This is what happned at your ActionSafeAction propertiy's setter too.
The equal of the above two method will be this property:
public class Foo
{
private string myMember;
public string MyMember
{
get { return myMember; }
set { myMember = value; }
}
}
I've recently got a small headache during unit testing one of my property setters. I wanted to setup my property to return a certain value and do not invoke setter logic because it has some heavy operations in there and I don't want that logic to affect my unit test.
I know I can move that logic to a method and then mock that new method instead but that problem made me curious and I've dug a little.
The results of my research is in FooTests class below, one of them using SetupProperty works, but makes me feel that this is not what this method is written for.
Is there a dedicated way to short-circuit setters in partial mocks in Moq?
Foo.cs:
public class Foo
{
private int _bar;
public virtual int Bar
{
get => _bar;
set
{
MagicNumber+=FooBar;
_bar = value;
}
}
private int _fooBar;
public virtual int FooBar
{
get => _fooBar;
set
{
//Complex and heavy logic that makes the magic number -value
MagicNumber = -value;
_fooBar = value;
}
}
public int MagicNumber { get; set; }
public Foo()
{
FooBar = 1;
}
}
FooTests.cs:
[TestFixture]
public class FooTests
{
//Using ordinary setup.
[TestCase(1, 2, 2, TestName = "BarSetter_BarSetToOneAndFooBarEqualsTwo_MagicNumberEqualsTwo")]
public void BarSetterTest(int bar, int fooBar, int expectedMagicNumber)
{
var fooPartialMock = new Mock<Foo> {CallBase = true};
fooPartialMock.Setup(x => x.FooBar).Returns(fooBar);
fooPartialMock.Object.Bar = bar;
Assert.AreEqual(expectedMagicNumber, fooPartialMock.Object.MagicNumber);
}
//Using callbacks.
[TestCase(1, 2, 2, TestName = "BarSetter_BarSetToOneAndFooBarEqualsTwo_MagicNumberEqualsTwo2")]
public void BarSetterTest2(int bar, int fooBar, int expectedMagicNumber)
{
var fooPartialMock = new Mock<Foo> { CallBase = true };
fooPartialMock.SetupSet(x => x.FooBar = It.IsAny<int>()).Callback<int>(x => {});
fooPartialMock.Object.Bar = bar;
Assert.AreEqual(expectedMagicNumber, fooPartialMock.Object.MagicNumber);
}
//Using SetupProperty.
[TestCase(1, 2, 2, TestName = "BarSetter_BarSetToOneAndFooBarEqualsTwo_MagicNumberEqualsTwo3")]
public void BarSetterTest3(int bar, int fooBar, int expectedMagicNumber)
{
var fooPartialMock = new Mock<Foo> { CallBase = true };
fooPartialMock.SetupProperty(x => x.FooBar);
fooPartialMock.Object.FooBar = fooBar;
fooPartialMock.Object.Bar = bar;
Assert.AreEqual(expectedMagicNumber, fooPartialMock.Object.MagicNumber);
}
}
The difference in results of the tests is caused by different behavior of Mock, that was configured. Method Setup In the first test just override getter method:
Specifies a setup on the mocked type for a call to a value returning method.
So in this case call of FooBar in constructor affects MagicNumber. Overloading of method SetupSet you used in second test is obsolete, and looks like it doesn't override the setter, it just set up an expectation, that you can verify later? on or add a callback:
Specifies a setup on the mocked type for a call to to a property setter, regardless of its value.
In this case FooBar in constructor affects the MagicNumber too. However FooBar setter is called twice: from constructor and from lambda, where it called with return value of It.IsAny<int>, which is 0. At last, SetupProperty from the third test sets up default property behavior:
Specifies that given property should have a property behavior, meaning that setting its value will cause it to be saved and later returned when the property is requested(this is also known as stubbing)
So FooBar in constructor doesn't affect MagicNumber in the third test, because the whole property is covered with stub, and you never get to FooBar setter. Therefore the third test is green. I suppose that configuration, that you implemented in third test, do what you need. You can combine it with the first one to make FooBar getter always return the same value:
fooPartialMock.SetupProperty(x => x.FooBar).Setup(x => x.FooBar).Returns(fooBar);
Hope it helps.
This might be a trivial question but I got really confused on this. I have a property with some logic in it.
private SomeObject _someProperty;
public SomeObject SomeProperty
{
get
{
Some checking here,
return _someProperty;
}
set
{
_someProperty = value;
}
}
Now what will happen when I am going to assign something to this property.
SomeProperty = new SomeClass();
What I was thinking here that get will be called here. It words it can be said like get SomeProperty and set that property. But what I have observed is that get is not called. Only setter is called (correct me if I am wrong here). I want to know if get is not called here what is its reason.
In simpler way to think about it.
GET: When something somewhere wants to GET value from here.
SET: When something somewhere wants to SET value here.
So, getters and setters answer to question from outside perspective. When you want to write value, SET is called. When you want to know current value, GET is called.
Properties are really just syntactic sugar for get/set methods. As the C# Programming Guide says:
A property is a member that provides a flexible mechanism to read, write, or compute the value of a private field. Properties can be used as if they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily and still helps promote the safety and flexibility of methods.
So your example really translates to something like:
private SomeObject _someProperty;
public SomeObject get_SomeProperty()
{
// Some checking here,
return _someProperty;
}
public void set_SomeProperty(SomeObject value)
{
_someProperty = value;
}
With the assignment becoming
set_SomeProperty(new SomeClass());
When thought of this way, it's clear that the getter is not called when you assign the property.
No, a property's getter is not called when setting the property, as can be easily demonstrated :
static class Program
{
static void Main(string[] args)
{
Foo foo = new Foo();
foo.Number = 7;
}
}
public class Foo
{
private int number;
public int Number
{
get
{
Console.WriteLine("In getter");
return this.number;
}
set
{
Console.WriteLine("In setter");
this.number = value;
}
}
}
Output:
In setter
No, get is called when you are reading the value of the property, set is called when you are assigning a value to the property.
What I was thinking here that get will be called here
Why? You are clear - you SET. And SET does not do anything in GET. Ergo, get is never called.
This IS the correct behaviour of mutator methods, you dont Read the Value from accessor
You don't need value of SomeProperty in this expression. If you wrote something like SomeProperty = SomeProperty + 1; then you will need a value of SomeProperty, and get will be called.
Actually
A property is a member that provides a flexible mechanism to read,
write, or compute the value of a private field. Properties can be used
as if they are public data members, but they are actually special
methods called accessors.
as it is said in msdn.
So consider it as a wrapper for something like this:
private SomeObject _someProperty;
public SomeObject getSomeProperty()
{
//Some checking here,
return _someProperty;
}
public void setSomeProperty(SomeObject value)
{
_someProperty = value;
}
It should be clear now unless you have the same question about setting the fields.
The C# "readonly" keyword is a modifier that when a field declaration includes it, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.
Now suppose I do want this "assign value once" constraint, but I would rather allow the assignment be done outside of constructors, a lazy/late evaluation/initialization maybe.
How could I do that? and is it possible to do it in a nice way, for example, is it possible to write some attribute to describe this?
If I understand your question correctly, it sounds like you just want to set a field's value once (the first time), and not allow it to be set after that. If that is so, then all the previous posts about using Lazy (and related) may be useful. But if you don't want to use those suggestions, perhaps you can do something like this:
public class SetOnce<T>
{
private T mySetOnceField;
private bool isSet;
// used to determine if the value for
// this SetOnce object has already been set.
public bool IsSet
{
get { return isSet; }
}
// return true if this is the initial set,
// return false if this is after the initial set.
// alternatively, you could make it be a void method
// which would throw an exception upon any invocation after the first.
public bool SetValue(T value)
{
// or you can make thread-safe with a lock..
if (IsSet)
{
return false; // or throw exception.
}
else
{
mySetOnceField = value;
return isSet = true;
}
}
public T GetValue()
{
// returns default value of T if not set.
// Or, check if not IsSet, throw exception.
return mySetOnceField;
}
} // end SetOnce
public class MyClass
{
private SetOnce<int> myReadonlyField = new SetOnce<int>();
public void DoSomething(int number)
{
// say this is where u want to FIRST set ur 'field'...
// u could check if it's been set before by it's return value (or catching the exception).
if (myReadOnlyField.SetValue(number))
{
// we just now initialized it for the first time...
// u could use the value: int myNumber = myReadOnlyField.GetValue();
}
else
{
// field has already been set before...
}
} // end DoSomething
} // end MyClass
Now suppose I do want this "assign value once" constraint, but I would rather allow the assignment be done outside of constructors
Note that lazy initialization is complicated, so for all of these answers you should be careful if you have multiple threads trying to access your object.
If you want to do this inside the class
You can use the C# 4.0 built-in lazy initialization features:
http://msdn.microsoft.com/en-us/library/dd997286.aspx
http://msdn.microsoft.com/en-us/library/dd642331.aspx
http://sankarsan.wordpress.com/2009/10/04/laziness-in-c-4-0-lazyt/
Or for older versions of C#, just supply a get method, and check if you're already initialized by using a backing field:
public string SomeValue
{
get
{
// Note: Not thread safe...
if(someValue == null)
{
someValue = InitializeSomeValue(); // Todo: Implement
}
return someValue;
}
}
If you want to do this outside the class
You want Popsicle Immutability:
http://blogs.msdn.com/b/ericlippert/archive/2007/11/13/immutability-in-c-part-one-kinds-of-immutability.aspx
http://msdn.microsoft.com/en-us/library/ms750509.aspx
http://csharpindepth.com/Talks.aspx (search for "popsicle immutability" and you'll find a video)
Basically:
You make the whole class writable, but add a Freeze method.
Once this freeze method is called, if users try to call setters or mutator methods on your class, you throw a ModifyFrozenObjectException.
You probably want a way for external classes to determine if your class IsFrozen.
BTW, I made up these names just now. My selections are admittedly poor, but there is no generically followed convention for this yet.
For now I'd recommend you create an IFreezable interface, and possibly related exceptions, so you don't have to depend on the WPF implementation. Something like:
public interface IFreezable
{
void Freeze();
bool IsFrozen { get; }
}
You can use the Lazy<T> class:
private readonly Lazy<Foo> _foo = new Lazy<Foo>(GetFoo);
public Foo Foo
{
get { return _foo.Value; }
}
private static Foo GetFoo()
{
// somehow create a Foo...
}
GetFoo will only be called the first time you call the Foo property.
This is know as the "once" feature in Eiffel. It is a major oversight in C#. The new Lazy type is a poor substitute since it is not interchangeable with its non-lazy version but instead requires you to access the contained value through its Value property. Consequently, I rarely use it. Noise is one of the biggest problems with C# code. Ideally, one wants something like this...
public once Type PropertyName { get { /* generate and return value */ } }
as oppose to the current best practice...
Type _PropertyName; //where type is a class or nullable structure
public Type PropertyName
{
get
{
if (_PropertyName == null)
_PropertyName = /* generate and return value */
return _PropertyName
}
}
I have an application that needs to determine whether a user has made a change to an object. So, when the object is first loaded, I create a deep copy (using serialization/deserialization) and save the copy to a separate field. The copy becomes myCurrentObject, and the original becomes myOriginalObject.
Now I need to test myCurrentObject for changes, which I plan to do by comparing it to myOriginalObject. All I need is a boolean result indicating whether any changes have been made. I have already determined that a simple hashcode comparison won't work. GetHashCode() generates different results for the two objects, even when there are no changes.
I am getting ready to write a method to do a property-by-property comparison, but before I do, I thought I would check to see if there is a simpler and more reusable way to test myCurrentObject to see if it has changed from myOriginalObject.
Any suggestions? Thanks for your help.
Instead could you implement a OnPropertyChanged event on each of your properties then you could just see if the event was ever thrown. If you specifically implement INotifyPropertyChanged, you will get the added benefit that you can do WPF binding if you ever want to.
If that isn't possible, you could probably implement a solution with reflection that would traverse both objects looking for differences.
What if an event is raised when a property is changed?
http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.propertychanged.aspx
You can override the GetHashCode method to reflect your needs.
The hash code can only tell you that an object has definately changed, it cannot tell you that an object definately hasn't changed (because different objects can return the same hash code).
Do investigate the Object.Equals method
You could add a dirty flag that indicates any field has changed. Set the dirty flag in the property set.
public bool IsDirty { get { return m_IsDirty; } }
public string Name {
set
{
m_Name = value;
m_IsDirty = true;
}
}
I usually do these kind of test like this:
public string sodomizar(myObject object)
{
return object.prop1.ToString() + object.prop2.ToString();
}
then test:
if(sodomizar(object1)==sodomizar(object2))
{
doStuff();
}
I would consider using an abstract superclass containing two things:
a flag that declares whether 'track
changes' is on or not (default to
false)
a Dictionary instance
that contains keyed value history
... then call Base.TrackChange(string, object) in each property accessor upon which you are interested in change. Where the string passed is the name of the Property (use reflection/pull the property name from the stack trace :- means the code in each method can be precisely the same) ... and the object passed is simply the meta variable 'value'. Some careful reflection/stack trace checking might mean you can remove the string parameter on this method ... means you keep entity Class C# coding requirements to a minimum.
The flag is there because basic state initialisation of the object means that property changes (set accessor calls) may be made until the object is fully hydrated the first time.
The Dictionary is there to enable trawling the changes (auditing?) and so forth. Scale this back to a second bool if all you need is simple true/false on the 'IsDirty' question.
Something like:
public abstract Class EntityBase
{
private bool _changesAreTracking = false;
private Dictionary<string, object> _changes = null;
public EntityBase() {}
public TrackChange(string propertyName, object value)
{
if(_changesAreTracking)
{
if(_changes == null) { _changes = new Dictionary<string, object>(); }
_changes.Add(propertyName, value);
}
}
public void StartTrackChanges()
{
_changesAreTracking = true;
}
public bool HasChanged()
{
bool returnThis = false;
if(_changes != null && _changes.Keys.Count() > 0)
{
returnThis = true;
}
return returnThis;
}
public bool HasChanged(string propertyName)
{
bool returnThis = false;
if(_changes != null && _changes.Keys.Contains(propertyName))
{
returnThis = true;
}
return returnThis;
}
}