Using Rhino Mocks for Effective Unit TestingMike ClementUtah Code CampSpring 2011mike@softwareontheside.com@mdclement
Unit Testing Defined“A piece of code that invokes another piece of code and checks the correctness of some assumptions afterward.”
Good Unit TestsAutomated and repeatableEasy to implementRemain for future useAnyone should be able to run itRun easily (push of a button)Run quickly
Simple Unit TestsNo dependencies
Simple Unit Test DemoPrime Factors
More Complex Unit TestsSimple only gets you so farNeed more sophisticated mechanismsIsolation or Mocking Frameworks to the rescue!Does necessitate classes/methods designed for testing
Test DoublesDummy objects are passed around but never actually used. Usually they are just used to fill parameter lists.Fake objects actually have working implementations, but usually take some shortcut which makes them not suitable for production (an in memory database is a good example).
More Test Doubles (Stubs)Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test. Stubs may also record information about calls, such as an email gateway stub that remembers the messages it 'sent', or maybe only how many messages it 'sent'.In Rhino Mocks:an object that you use in order to pass to the code under test. expectations will never be verified. properties will automatically behave like normal properties, and you can't set expectations on them.IMPORTANT: A stub will never cause a test to fail.MockRepository.GenerateStub<T>()
Rhino Mocks FeaturesChoice of "Arrange, Act, and Assert" or "Explicit record, replay, and verify" models for expectations.Support for Generics, C# Lambda expressions, and other C# 3.0 and .NET 3.5 featuresWorking with strongly typed mocks.Expectations based on:Arguments matchingConstraints matchingCustom callback to verify the expected arguments using your own codeCalling your delegates to decide what to doSetting actions on methods, return specific value, or throw an exception.Much more.
Stubs Demo
Simple and Inline ConstraintsSpecifyrepository.Stub(x => x.UpdateSession(session))Ignore AllIgnoreArguments()Arg<T>.Is.AnythingArg<T>.Is.Null
Arg ConstraintsArg<T>.IsEqual(object), NotEqual(object)	Comparison using EqualsGreaterThan(object), LessThan(object), LessThanOrEqual(object), GreaterThanOrEqual(object)	Comparison using >, <, >= and <= operatorsSame(object), NotSame(object)	Reference equalityAnything()	No constraintsNull(), NotNull()	Reference is null or not nullTypeOf(Type), TypeOf<T>()	Argument is of a certain typeMatching<T>(Predicate<T>)	Argument matches a predicate (.NET 3.5: see Arg<T>.Matches). Example: Arg<string>.Is.Matching(delegate(string s) { return s.Length == 2; }IsIn(object)	Enumerable argument includes the specified objectArg<T>.ListOneOf(IEnumerable)	Argument is in the specified listEqual(IEnumerable)	All items in the enumerable argument are compared to the items in the specified list.Count(AbstractConstraint)	Constraints to the Count property of the argument.Element(int, AbstractConstraint)	Element at the specified index meets the constraint.ContainsAll(IEnumerable)	The enumerable argument contains at least the specified items.Arg<T>.PropertyAllPropertiesMatch(object)	All the public properties and public fields are compared to the properties in the specified object. The comparesion is recusive if public properties or fields are complex types.IsNotNull(string propertyName), IsNull(string propertyName)	Property of the given name is or is not nullValue(string propertyName, object expectedValue)	The property of the given name is equal to the expected value.Value(string propertyName, AbstractConstraint constraint)	Property of the given Name meets the constraint.Arg.TextStartsWith(string), EndsWith(string), Contains(string)	String starts with, ends with or contains the specified textLike(string regex)	Property matches to the regular expressionArg<T>.MatchesArg<T>.Matches(Expression)	Only in .NET 3.5 you can specify the constraint as a lambda expression, e.g. Arg<int>.Matches(x => x > 3)Arg<T>.Matches(AbstractConstraint)	Specify Rhino Mocks Constraints, e.g. Arg<int>.Matches(Is.GreaterThan(0) && Is.LessThan(10))http://www.ayende.com/wiki/Rhino+Mocks+3.5.ashx#ConstraintsReference
More Test Doubles (Mocks)Mocks are objects pre-programmed with expectations which form a specification of the calls they are expected to receive.An object that we can set expectations on, and which will verify that the expected actions have indeed occurred. http://martinfowler.com/articles/mocksArentStubs.html
MocksStrict vs. DynamicUse Dynamic Mocks… Strict not recommendedMockRepository.GenerateMock<T>()
Mocks Demo
Events![Test] public void RaisingEvent () { varmocks = new MockRepository();IView view = mocks.DynamicMock<IView>();Presenter p = new Presenter(view);view.Raise(x => x.Load += null, this, EventArgs.Empty);Assert.IsTrue(p.OnLoadCalled); }
Good Unit Testing Resources!The Art of Unit Testing: With Examples in .NetPragmatic Unit Testing in C# with NUnit, 2nd Editionhttp://www.ayende.com/wiki/Rhino+Mocks.ashx
Thank you to our sponsors!Platinum SponsorsGold SponsorsSilver SponsorsBronze Sponsors

Using Rhino Mocks for Effective Unit Testing

  • 1.
    Using Rhino Mocksfor Effective Unit TestingMike ClementUtah Code CampSpring 2011mike@softwareontheside.com@mdclement
  • 2.
    Unit Testing Defined“Apiece of code that invokes another piece of code and checks the correctness of some assumptions afterward.”
  • 3.
    Good Unit TestsAutomatedand repeatableEasy to implementRemain for future useAnyone should be able to run itRun easily (push of a button)Run quickly
  • 4.
  • 5.
    Simple Unit TestDemoPrime Factors
  • 6.
    More Complex UnitTestsSimple only gets you so farNeed more sophisticated mechanismsIsolation or Mocking Frameworks to the rescue!Does necessitate classes/methods designed for testing
  • 7.
    Test DoublesDummy objects arepassed around but never actually used. Usually they are just used to fill parameter lists.Fake objects actually have working implementations, but usually take some shortcut which makes them not suitable for production (an in memory database is a good example).
  • 8.
    More Test Doubles(Stubs)Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test. Stubs may also record information about calls, such as an email gateway stub that remembers the messages it 'sent', or maybe only how many messages it 'sent'.In Rhino Mocks:an object that you use in order to pass to the code under test. expectations will never be verified. properties will automatically behave like normal properties, and you can't set expectations on them.IMPORTANT: A stub will never cause a test to fail.MockRepository.GenerateStub<T>()
  • 9.
    Rhino Mocks FeaturesChoiceof "Arrange, Act, and Assert" or "Explicit record, replay, and verify" models for expectations.Support for Generics, C# Lambda expressions, and other C# 3.0 and .NET 3.5 featuresWorking with strongly typed mocks.Expectations based on:Arguments matchingConstraints matchingCustom callback to verify the expected arguments using your own codeCalling your delegates to decide what to doSetting actions on methods, return specific value, or throw an exception.Much more.
  • 10.
  • 11.
    Simple and InlineConstraintsSpecifyrepository.Stub(x => x.UpdateSession(session))Ignore AllIgnoreArguments()Arg<T>.Is.AnythingArg<T>.Is.Null
  • 12.
    Arg ConstraintsArg<T>.IsEqual(object), NotEqual(object) Comparisonusing EqualsGreaterThan(object), LessThan(object), LessThanOrEqual(object), GreaterThanOrEqual(object) Comparison using >, <, >= and <= operatorsSame(object), NotSame(object) Reference equalityAnything() No constraintsNull(), NotNull() Reference is null or not nullTypeOf(Type), TypeOf<T>() Argument is of a certain typeMatching<T>(Predicate<T>) Argument matches a predicate (.NET 3.5: see Arg<T>.Matches). Example: Arg<string>.Is.Matching(delegate(string s) { return s.Length == 2; }IsIn(object) Enumerable argument includes the specified objectArg<T>.ListOneOf(IEnumerable) Argument is in the specified listEqual(IEnumerable) All items in the enumerable argument are compared to the items in the specified list.Count(AbstractConstraint) Constraints to the Count property of the argument.Element(int, AbstractConstraint) Element at the specified index meets the constraint.ContainsAll(IEnumerable) The enumerable argument contains at least the specified items.Arg<T>.PropertyAllPropertiesMatch(object) All the public properties and public fields are compared to the properties in the specified object. The comparesion is recusive if public properties or fields are complex types.IsNotNull(string propertyName), IsNull(string propertyName) Property of the given name is or is not nullValue(string propertyName, object expectedValue) The property of the given name is equal to the expected value.Value(string propertyName, AbstractConstraint constraint) Property of the given Name meets the constraint.Arg.TextStartsWith(string), EndsWith(string), Contains(string) String starts with, ends with or contains the specified textLike(string regex) Property matches to the regular expressionArg<T>.MatchesArg<T>.Matches(Expression) Only in .NET 3.5 you can specify the constraint as a lambda expression, e.g. Arg<int>.Matches(x => x > 3)Arg<T>.Matches(AbstractConstraint) Specify Rhino Mocks Constraints, e.g. Arg<int>.Matches(Is.GreaterThan(0) && Is.LessThan(10))http://www.ayende.com/wiki/Rhino+Mocks+3.5.ashx#ConstraintsReference
  • 13.
    More Test Doubles(Mocks)Mocks are objects pre-programmed with expectations which form a specification of the calls they are expected to receive.An object that we can set expectations on, and which will verify that the expected actions have indeed occurred. http://martinfowler.com/articles/mocksArentStubs.html
  • 14.
    MocksStrict vs. DynamicUseDynamic Mocks… Strict not recommendedMockRepository.GenerateMock<T>()
  • 15.
  • 16.
    Events![Test] public voidRaisingEvent () { varmocks = new MockRepository();IView view = mocks.DynamicMock<IView>();Presenter p = new Presenter(view);view.Raise(x => x.Load += null, this, EventArgs.Empty);Assert.IsTrue(p.OnLoadCalled); }
  • 17.
    Good Unit TestingResources!The Art of Unit Testing: With Examples in .NetPragmatic Unit Testing in C# with NUnit, 2nd Editionhttp://www.ayende.com/wiki/Rhino+Mocks.ashx
  • 18.
    Thank you toour sponsors!Platinum SponsorsGold SponsorsSilver SponsorsBronze Sponsors