Created
June 22, 2014 01:49
-
-
Save urasandesu/dab9e7d9c322a1cc2cf3 to your computer and use it in GitHub Desktop.
How to use Prig in combination with Moq.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Moq; | |
using NUnit.Framework; | |
using System; | |
using System.ComponentModel; | |
using System.Prig; | |
using System.Runtime.CompilerServices; | |
using Urasandesu.Prig.Framework; | |
namespace MockingDelegatesSample | |
{ | |
[TestFixture] | |
public class MockingDelegatesTest | |
{ | |
[Test] | |
public void ValueWithRandomAdded_should_raise_PropertyChanged_event_with_its_name() | |
{ | |
// Arrange | |
var notifyingObject = new NotifyingObject(); | |
var mockHandler = new Mock<PropertyChangedEventHandler>(); | |
mockHandler.Setup(_ => _(It.IsAny<object>(), It.IsAny<PropertyChangedEventArgs>())); | |
notifyingObject.PropertyChanged += mockHandler.Object; | |
// Act | |
notifyingObject.ValueWithRandomAdded = 42; | |
// Assert | |
mockHandler.Verify(_ => _(It.Is<object>(o => o == notifyingObject), It.Is<PropertyChangedEventArgs>(o => o.PropertyName == "ValueWithRandomAdded")), Times.Once()); | |
} | |
[Test] | |
public void ValueWithRandomAdded_should_hold_passed_value_plus_random_value() | |
{ | |
using (new IndirectionsContext()) | |
{ | |
// Arrange | |
var notifyingObject = new NotifyingObject(); | |
var mockNext = new Mock<IndirectionFunc<Random, int>>(); | |
mockNext.Setup(_ => _(It.IsAny<Random>())).Returns(10); | |
PRandom.Next.Body = mockNext.Object; | |
// Act | |
notifyingObject.ValueWithRandomAdded = 32; | |
var actual = notifyingObject.ValueWithRandomAdded; | |
// Assert | |
mockNext.Verify(_ => _(It.IsAny<Random>()), Times.Once()); | |
Assert.AreEqual(42, actual); | |
} | |
} | |
class NotifyingObject : INotifyPropertyChanged | |
{ | |
public event PropertyChangedEventHandler PropertyChanged; | |
int m_valueWithRandomAdded; | |
public int ValueWithRandomAdded | |
{ | |
get { return m_valueWithRandomAdded; } | |
set | |
{ | |
m_valueWithRandomAdded = value; | |
m_valueWithRandomAdded += new Random((int)DateTime.Now.Ticks).Next(); | |
OnPropertyChanged(); | |
} | |
} | |
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = "") | |
{ | |
var handler = PropertyChanged; | |
if (handler == null) | |
return; | |
handler(this, new PropertyChangedEventArgs(propertyName)); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment