C#: Generics Equality

When comparing objects using generics in C#, the behaviour is slightly different to normal comparison behaviour – notably that the compiler will default to using the more generic equals method equals(object obj)) as opposed to specific type based equals that you may have declared in a class. To overcome this, your class must implement the generic IEquatable<T> interface (instead of just overriding / overloading the equals method). A simple example is shown below:

internal class Foo : IEquatable<Foo>
{
    public int Property1 { get; set; }
    public bool Equals(Foo obj)
    {
        if (!this.Property1.Equals(obj.Property1)) return false;
        return true;
    }
}

internal class DoSomething
{
    public void Something()
    {
        var thing1 = new Foo { Property1 = 23 };
        var thing2 = new Foo { Property1 = 23 };
        this.Compare<Foo>(thing1, thing2);
    }

    private void Compare<T>(T expected, T actual) where T : IEquatable<T>
    {
        if (expected.Equals(actual))
            Console.WriteLine(“Input was equal”);
        else
            Console.WriteLine(“Input was not equal”);
    }
}

Note that this become more complicated however when comparing an instance of a base class to an instance of a deriving class. Normally you would probably want to do this using the base class implementation of equals, however some extra work is required to achieve the correct behaviour with generics (notably a constraint on your comparison method and a cast to IEquatable<T>.

internal class Foo : IEquatable<Foo>
{
    public int Property1 { get; set; }

    public bool Equals(Foo obj)
    {
        if (!this.Property1.Equals(obj.Property1)) return false;
        return true;
    }
}

internal class Bar : Foo
{
    public string Property2 { get; set; }
}

internal class DoSomething
{
    public void Something()
    {
        var thing1 = new Foo { Property1 = 23 };
        var thing2 = new Bar { Property1 = 23, Property2 = “Hello” };
        this.Compare<Foo, Bar> (thing1, thing2);
    }

    private void Compare<T, V>(T expected, V actual) where V : class, T, IEquatable<T>
    {
        if (((IEquatable<T>)expected).Equals(actual))
            Console.WriteLine(“Input was equal”);
        else
            Console.WriteLine(“Input was not equal”);
    }
}

Note that this link discusses this in more detail.

WCF: Consuming Xml Rest Service

Below is an example of how to consume a restful service that returns xml date from wcf client. This example is based on a discography service that returns releases for a specific artist. The name of the artist is passed in the query string.

Example xml returned by service:

<Artist>
  <Name>Example Artist</Name>
  <Genre>Example Genre</Genre>
  <Tracks>
    <Track>
      <Title>Track 1</Title>
      <Released>2008-10-03T00:00:00</Released>
    </Track>
    <Track>
      <Title>Track 2</Title>
      <Released>2008-10-03T00:00:00</Released>
    </Track>
  </Tracks>
</Artist>

To consume this, first declare the bindings and endpoints in the appropriate app.config / web.config

<?xml version=”1.0″ encoding=”utf-8″ ?>
<configuration>
  <system.serviceModel>
    <bindings>
      <webHttpBinding>
        <binding name=”ArtistBinding” maxReceivedMessageSize=”65536″>
          <!– Security is integrated auth –>
          <security mode=”TransportCredentialOnly”>
            <transport clientCredentialType=”Windows” />
          </security>
        </binding>
      </webHttpBinding>
    </bindings>
    <client>
      <endpoint address=”
http://localhost”
          binding=”webHttpBinding” bindingConfiguration=”ArtistBinding”
          contract=”RestWcfClient.IArtist”
          name=”ArtistService” />
    </client>
  </system.serviceModel>
</configuration>

Define the contract using the the WebGet attribute. Note the way the artist name is passed through on the query string (ideally a restful service will rely on nouns as opposed to query string verbs), Also note that the type “Artist” is defined later.

using System.ServiceModel;
using System.ServiceModel.Web;

namespace RestWcfClient
{
    [ServiceContract]
    public interface IArtist
    {

        [XmlSerializerFormat]
        [OperationContract]
        [WebGet(
            BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Xml,
            UriTemplate = “RestServiceForWcfExample/Discog.ashx?artist={artistName}”)]
        Artist GetDiscography(string artistName);
    }
}

To consume from the method define in the template, use the following code in your client:

// “ArtistService” refers to the named endpoint in the web.config / app.config
using (var cf = new WebChannelFactory<IArtist>(“ArtistService”))
{
    try
    {
        var s = cf.CreateChannel();
        var result = s.GetDiscography(“An artist”);
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        cf.Abort();
        throw;
    }
}

The data types used in this example are shown below (these need only to exist in the client). Note that the name of types should match the name of the xml elements returned from the rest service.

[XmlType(AnonymousType = true, Namespace = “”)]
[XmlRoot(Namespace = “”, IsNullable = false)]
public class Artist
{
    public string Name { get; set; }
    public string Genre { get; set; }
    public List<Track> Tracks { get; set; }
}

public class Track
{
    public string Title { get; set; }
    public DateTime Released { get; set; }
}

Some More RhinoMocks Examples

Here is a little bit of example code testing readonly / writeonly properties on a interface, as well as void methods

var mockRepository = new MockRepository();
var foo = mockRepository.StrictMock<IFoo>();

using (mockRepository.Record())
{
  // Test property is set set to 88;
  foo.TestProperty = 88;

  // Force return value of property to 99
  Expect.Call(foo.TestProperty).Return(99);

  // Force return value of property to 99
  Expect.Call(foo.TestReadOnlyProperty).Return(99);

  // Test property is set to 297
  // could also do Expect.Call(() => foo.TestWriteOnlyProperty = 297);
  foo.TestWriteOnlyProperty = 297;

  // Ensure void method is called (no params)
  // Could also do Expect.Call(() => foo.TestVoidMethodNoParams());
  foo.TestVoidMethodNoParams();
  // Ensure method is called with a specific param.
  // Could also do Expect.Call(() => foo.TestVoidMethod(297));
  // if we wanted to specify stuff on expect.call (e.g. ignore args)
  foo.TestVoidMethod(297);
}

using (mockRepository.Playback())
{
  var bar = new Bar(foo);
  bar.DoSomething();
}

Here is a good RhinoMocks quick reference guide: http://orand.blogspot.com/2007/12/rhino-mocks-quick-reference.html

Unit Tests: Mocking a base class method

This example talks about testing a method in a subclass that calls a base class method. Calling the base class method has side effects (e.g relies on a database / httpcontext, or in this example calls console.writeline), so need to be mocked out in order to allow testing of the method in the subclass.

To allow this to be mocked when called from tests, an additional constructor can be create (i.e. as per standard Dependency Injection), that passes in a new implementation of the method in the base class (via the Action / Func keyword). A delegate exists in the subclass that can then be called via an overload of the mocked method (as long as that method was virtual in the base).

Note that when not testing, the normal constructor is called – this just assigns the base implementation of the method to the delegate, thus giving normal behaviour. The code below demonstrates:

The base class contains a method that needs to be mocked as it has side effects:

public abstract class BaseClass
{
    protected virtual void DoSomethingUsingContext(string message)
    {
        Console.WriteLine(“Doing something against the context – e.g. httpcontext: {0}”, message);
    }

    public abstract void DoSomethingImportant();       
}

We want to test “DoSomethingImportant” on the deriving class shown below. This requires a dependency injection constructor to allow  “DoSomethingUsingContext” to be mocked. Note that “Action<string>” defines a delegate with the same signature as “DoSomethingUsingContext”.

public class ConcreteClass : BaseClass
{
    Action<string> doSomethingUsingContext;

    public ConcreteClass(Action<string> doSomethingUsingContextImplementation)
    {
        this.doSomethingUsingContext = doSomethingUsingContextImplementation;
    }

    public ConcreteClass()
    {
        this.doSomethingUsingContext = base.DoSomethingUsingContext;
    }

    protected override void DoSomethingUsingContext(string message)
    {
        this.doSomethingUsingContext(message);
    }

    public override void DoSomethingImportant()
    {
        // Do something important here

        this.DoSomethingUsingContext(“A message about something”);
    }
}

Finally, we can inject a mock implementation of “DoSomethingUsingContext” from our unit test (note in this example we write to debug listeners instead of the console – when debugging you can see output in the output window of visual studio).

[TestMethod]
public void TestMethod1()
{
    bool doSomethingUsingContextWasCalled = false;
    Action<string> testImplementation = (x) => { Debug.WriteLine(x); doSomethingUsingContextWasCalled = true; };

    ConcreteClass myClass = new ConcreteClass(testImplementation);
    myClass.DoSomethingImportant();

    Assert.IsTrue(doSomethingUsingContextWasCalled);
}