-
April 4th, 2012asp.net, Test Driven DevelopmentDuring a recent XP programming course we made use of the Moq’ing framework. I’d not used this before so tried to come up with some example moq basic tests. There are several tutorials on the internet which offer up the basics so do hunt around. Hopefully the following provides some simple examples for people to get started with.
The following code relies on the following assemblies:
- nunit.framework – available from http://www.nunit.org/
- moq – available from http://code.google.com/p/moq/
The real crux of TDD is that you program your functionality to interfaces – here we have a simple interface and dto:
public interface IMyInterface { int IntMethod(int value); int HarderIntMethod(int value, int anotherValue); MyObject MyObjectMethod(int value); } public class MyObject { public virtual string MyVirtualProperty { get; set; } public string MyProperty { get; set; } }Note the importance of the virtual property in MyObject will be highlighted in the tests. In the following examples not all the tests pass – this is intentional! Failing tests are included to demonstrate specific features of Moq. Apologies for the long dump of test code – the idea is really to copy it into a test class and let NUnit do the work.
[TestFixture] public class MyTests { [Test] [TestCase(1, TestName = "1")] public void A_TestMockBehaviourDefault(int value) { Mock<IMyInterface> myInterface = new Mock<IMyInterface>(); int result = myInterface.Object.IntMethod(value); //we havent setup mock for value = 1 Assert.AreEqual(value, result); myInterface.Verify(); } [Test] [TestCase(1, TestName = "1")] public void B_TestMockBehaviourStrict(int value) { Mock<IMyInterface> myInterface = new Mock<IMyInterface>(MockBehavior.Strict); int result = myInterface.Object.IntMethod(value); //now in strict mode //again, we havent setup mock for value = 1 Assert.AreEqual(value, result); myInterface.Verify(); } [Test] [TestCase(1, TestName = "1")] [TestCase(2, TestName = "2")] public void C_TestMockBehaviourStrictWithSpecificValue(int value) { Mock<IMyInterface> myInterface = new Mock<IMyInterface>(MockBehavior.Strict); myInterface.Setup(a => a.IntMethod(1)).Returns(1); int result = myInterface.Object.IntMethod(value); //we have setup the mock for value = 1 but not value = 2 Assert.AreEqual(value, result); myInterface.Verify(); } [Test] [TestCase(1, TestName = "1")] [TestCase(2, TestName = "2")] public void D_TestMockBehaviourStrictWithTypedValue(int value) { Mock<IMyInterface> myInterface = new Mock<IMyInterface>(MockBehavior.Strict); myInterface.Setup(a => a.IntMethod(It.IsAny<int>())).Returns((int a) => a); int result = myInterface.Object.IntMethod(value); //any int will pass Assert.AreEqual(value, result); myInterface.Verify(); } private int _count = 0; [Test] [TestCase(1, TestName = "1")] [TestCase(2, TestName = "2")] public void E_TestMockBehaviourStrictWithTypedValueAndCallback(int value) { Mock<IMyInterface> myInterface = new Mock<IMyInterface>(MockBehavior.Strict); myInterface.Setup(a => a.IntMethod(It.IsAny<int>())).Returns((int a) => a).Callback(() => _count++); int result = myInterface.Object.IntMethod(value); //we can log callbacks before or after the Returns call Console.WriteLine(String.Format("Called E_TestMockBehaviourStrictWithTypedValueAndCallback {0} times", _count)); Assert.AreEqual(value, result); myInterface.Verify(); } [Test] [TestCase(1, TestName = "1")] [TestCase(2, TestName = "2")] public void E1_TestMockBehaviourStrictWithTypedValueAndCallbackBefore(int value) { Mock<IMyInterface> myInterface = new Mock<IMyInterface>(MockBehavior.Strict); //callbacks can happen before and after the Returns call myInterface.Setup(a => a.IntMethod(It.IsAny<int>())).Callback(() => Console.WriteLine("before")).Returns((int a) => a).Callback(() => Console.WriteLine("after")); int result = myInterface.Object.IntMethod(value); Assert.AreEqual(value, result); myInterface.Verify(); } [Test] [TestCase(1, TestName = "1")] [TestCase(2, TestName = "2")] [ExpectedException(typeof(Exception))] public void F_TestMockBehaviourStrictWithException(int value) { Mock<IMyInterface> myInterface = new Mock<IMyInterface>(MockBehavior.Strict); //this can throw specific exceptions if we want //catching at a test level is a bit loose since other code could exception - see F1 for alternative myInterface.Setup(a => a.IntMethod(It.IsAny<int>())).Throws<Exception>(); int result = myInterface.Object.IntMethod(value); myInterface.Verify(); } [Test] [TestCase(1, TestName = "1")] [TestCase(2, TestName = "2")] public void F1_TestMockBehaviourStrictWithException(int value) { Mock<IMyInterface> myInterface = new Mock<IMyInterface>(MockBehavior.Strict); //this can throw specific exceptions if we want myInterface.Setup(a => a.IntMethod(It.IsAny<int>())).Throws<Exception>(); //here we can catch specific exceptions Assert.Throws<Exception>(() => myInterface.Object.IntMethod(value)); myInterface.Verify(); } [Test] [TestCase(1, TestName = "1")] [TestCase(2, TestName = "2")] public void G_TestMockBehaviourStrictVerify(int value) { Mock<IMyInterface> myInterface = new Mock<IMyInterface>(MockBehavior.Strict); myInterface.Setup(a => a.IntMethod(It.IsAny<int>())).Returns((int a) => a).Verifiable(); myInterface.Setup(a => a.HarderIntMethod(It.IsAny<int>(), (It.IsAny<int>()))).Returns((int a, int b) => a).Verifiable(); int result = myInterface.Object.IntMethod(value); //we havent called HarderIntMethod myInterface.Verify(); } [Test] [TestCase(1, TestName = "1")] [TestCase(2, TestName = "2")] public void H_TestMockBehaviourStrictVerifySuccess(int value) { Mock<IMyInterface> myInterface = new Mock<IMyInterface>(MockBehavior.Strict); myInterface.Setup(a => a.IntMethod(It.IsAny<int>())).Returns((int a) => a).Verifiable(); myInterface.Setup(a => a.HarderIntMethod(It.IsAny<int>(), It.IsAny<int>())).Returns((int a, int b) => a).Verifiable(); int result = myInterface.Object.IntMethod(value); int anotherResult = myInterface.Object.HarderIntMethod(value, value); myInterface.Verify(); } [Test] [TestCase(1, TestName = "1")] [TestCase(2, TestName = "2")] public void I_TestMockBehaviourStrictWithTypedValueAndLogicOnInput(int value) { Mock<IMyInterface> myInterface = new Mock<IMyInterface>(MockBehavior.Strict); //setup can perform logic based on input to determine return value(s) myInterface.Setup(a => a.IntMethod(It.Is<int>(b => b % 2 == 0))).Returns((int a) => a); myInterface.Setup(a => a.IntMethod(It.Is<int>(b => b % 2 != 0))).Returns((int a) => -a); int result = myInterface.Object.IntMethod(value); Assert.AreEqual(value, result); myInterface.Verify(); } [Test] [TestCase(1, TestName = "1")] [TestCase(2, TestName = "2")] [TestCase(4, TestName = "4")] public void J_TestMockBehaviourStrictWithTypedValueAndRangeLogicOnInput(int value) { Mock<IMyInterface> myInterface = new Mock<IMyInterface>(MockBehavior.Strict); //rather than specific logic, instead we can make use of Ranges myInterface.Setup(a => a.IntMethod(It.IsInRange<int>(0,3, Range.Inclusive))).Returns((int a) => a); int result = myInterface.Object.IntMethod(value); Assert.AreEqual(value, result); //we haven't setup a return value for 4 myInterface.Verify(); } [Test] [TestCase(1, TestName = "1")] [TestCase(2, TestName = "2")] public void K_TestMockBehaviourStrictWithProperties(int value) { Mock<IMyInterface> myInterface = new Mock<IMyInterface>(MockBehavior.Strict); //we can manipulate objects being returned myInterface.Setup(a => a.MyObjectMethod(value)).Returns((int a) => new MyObject() { MyProperty = a.ToString() }); MyObject result = myInterface.Object.MyObjectMethod(value); Assert.AreEqual(value.ToString(), result.MyProperty); myInterface.Verify(); } [Test] public void L_TestMockBehaviourStrictWithPropertiesVerifyGet() { Mock<MyObject> myObject = new Mock<MyObject>(MockBehavior.Strict); //this is where you need virtual properties myObject.Setup(a => a.MyProperty).Returns("blah"); myObject.Verify(); myObject.VerifyGet(a => a.MyProperty); } [Test] public void L1_TestMockBehaviourStrictWithPropertiesVerifyGet() { Mock<MyObject> myObject = new Mock<MyObject>(MockBehavior.Strict); myObject.Setup(a => a.MyVirtualProperty).Returns("blah"); myObject.Verify(); //we have never accessed MyVirtualProperty hence the VerifyGet fails myObject.VerifyGet(a => a.MyVirtualProperty); } [Test] public void L2_TestMockBehaviourStrictWithPropertiesVerifyGet() { Mock<MyObject> myObject = new Mock<MyObject>(MockBehavior.Strict); myObject.Setup(a => a.MyVirtualProperty).Returns("blah"); Assert.IsNotEmpty(myObject.Object.MyVirtualProperty); myObject.Verify(); //we have accessed both properties myObject.VerifyGet(a => a.MyVirtualProperty); } [Test] public void L3_TestMockBehaviourStrictWithPropertiesSetupProperty() { Mock<MyObject> myObject = new Mock<MyObject>(MockBehavior.Strict); //rather than setup and then adding Returns method, SetupProperty achieves the same thing myObject.SetupProperty(a => a.MyVirtualProperty, "blah"); Assert.IsNotEmpty(myObject.Object.MyVirtualProperty); myObject.Verify(); myObject.VerifyGet(a => a.MyVirtualProperty); } [Test] [TestCase(1, TestName = "1")] [TestCase(2, TestName = "2")] public void M_TestMockBehaviourStrictWithTypedValueAndDetailedCallback(int value) { Mock<IMyInterface> myInterface = new Mock<IMyInterface>(MockBehavior.Strict); //Callback and Returns can both deal with multiple parameters via Generics or parameters. // M1 shows the opposite of each myInterface.Setup(a => a.HarderIntMethod(It.IsAny<int>(), It.IsAny<int>())) .Returns((int a, int b) => a) .Callback<int, int>((a, b) => Console.WriteLine("A is " + a + " B is " + b)); int result = myInterface.Object.HarderIntMethod(value, value + 1); Assert.AreEqual(value, result); myInterface.Verify(); } [Test] [TestCase(1, TestName = "1")] [TestCase(2, TestName = "2")] public void M1_TestMockBehaviourStrictWithTypedValueAndDetailedCallbackAlternativeSyntax(int value) { Mock<IMyInterface> myInterface = new Mock<IMyInterface>(MockBehavior.Strict); //demonstrates the opposite of M in terms of the syntax required into Callback and Returns myInterface.Setup(a => a.HarderIntMethod(It.IsAny<int>(), It.IsAny<int>())) .Returns<int , int>((a, b) => a) .Callback((int a, int b) => Console.WriteLine("A is " + a + " B is " + b)); int result = myInterface.Object.HarderIntMethod(value, value + 1); Assert.AreEqual(value, result); myInterface.Verify(); } }Here is the expected results when evaluated in NUnit:
-
July 8th, 2011asp.netWhen building large scale applications a very useful design pattern to adopt is dependency injection. An example of this is programming to interfaces such that the implementation of each interface can be interchanged.
In this post I will demonstrate some examples of how you can go about adding functionality to interfaces with extension methods.
Consider the following example with some demo interfaces and classes:
//Incident is a simple dto which could include things like category, severity, message, date etc public class Incident { public string Message { get; set; } public Severity IncidentSeverity { get; set; } } //Incident severity public enum Severity { Info, Warn, Fatal } //Interface for our logging public interface ILog { //Write incident to log void Write(Incident incident); } //Implementation of our log - behind the scenes this could log to any format public class Log : ILog { public void Write(Incident incident) { //write to required log eg sql / xml } } public class MyProgram { public void DoSomething() { //perform tasks //access instance of log //note: DependencyInjectionLogic.Instantiate is //pseudo code for this, libraries are available to perform this kind of operation //the idea being that Log is the selected implementation ILog log = DependencyInjectionLogic.Instantiate<ILog>(); log.Write(new Incident() { IncidentSeverity = Severity.Info, Message = "Message" }); } }This is all well and good – the user can write log entries with the following line:
log.Write(new Incident() { IncidentSeverity = Severity.Info, Message = "Message" });So, how can we achieve:
ILog.Warn("message");The interface cannot contain any implementation. One solution would be to use abstract classes for the base class however that goes against the principal of programming to interfaces.
How about extension methods? Using the following examples we can add these shorthand methods to our ILog hiding some of the complexity / repeated code:
public static class ILogExtensions { public static void Warn(this ILog log, string message) { Incident incident = new Incident() { IncidentSeverity = Severity.Warn, Message = message }; log.Write(incident); } }If you setup the extension methods in the same namespace as your interface, you will now have available:
ILog.Warn("message"); -

When building web controls, a common scenario is how to cascade control parameters to the control from the markup (or code-behind). Within Sitecore controls this is typically the Field you want to render.
<tc:SText runat="server" Field="Title" HideIfEmpty="true" />
This approach to programming controls works very well until the set of parameters becomes very long or the control doesnt need to know about each parameter. Consider embedding a flash movie, the number of parameters to code could be huge.
In the flash example, often the parameters aren’t needed by your c# code, instead they just to be rendered to the markup.
<pf:SFlash runat="server" Field="Flash Item" Width="384" Height="380"> <ParametersTemplate> <param name="quality" value="high" /> <param name="bgcolor" value="#006699" /> ... <param name="salign" value="" /> <param name="allowScriptAccess" value="sameDomain" /> <param name="flashVars" value='dataURL=<%= FeedUrl() %>' /> </ParametersTemplate> </pf:SFlash>One useful tip is that you can get information from your code behind into the template markup eg
<%= FeedUrl() %>
To build the control you need to add the following attribute:
[ParseChildren(true)] public class SFlash : Control
And then the template you want to use:
[Browsable(false), DefaultValue(null), PersistenceMode(PersistenceMode.InnerProperty)] public virtual ITemplate ParametersTemplate { get { return _parametersTemplate; } set { _parametersTemplate = value; } } private ITemplate _parametersTemplate;The content of the template can be extracted as a string with the following:
PlaceHolder placeholder = new PlaceHolder(); if (ParametersTemplate != null) { ParametersTemplate.InstantiateIn(placeholder); } StringWriter stringWriter = new StringWriter(); HtmlTextWriter writer = new HtmlTextWriter(stringWriter); placeholder.RenderControl(writer);Note, based on the chosen implementation, you may not need the content of the template as a string. Instead you could simply instantiate to the control’s child controls.
Tags: sitecore -


