DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • TDD Typescript NestJS API Layers with Jest Part 1: Controller Unit Test
  • Chaos Mesh — A Solution for System Resiliency on Kubernetes
  • Clean Unit Testing
  • The Anatomy of Good Unit Testing

Trending

  • MCP Servers: The Technical Debt That Is Coming
  • How To Build Resilient Microservices Using Circuit Breakers and Retries: A Developer’s Guide To Surviving
  • The Future of Java and AI: Coding in 2025
  • Monolith: The Good, The Bad and The Ugly
  1. DZone
  2. Coding
  3. Languages
  4. Comparing Two Objects Using Assert.AreEqual()

Comparing Two Objects Using Assert.AreEqual()

In order to change the way two objects are compared in an assert we only need change the behavior of one of them — the expect value.

By 
Dror Helper user avatar
Dror Helper
·
Mar. 30, 16 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
110.7K Views

Join the DZone community and get the full member experience.

Join For Free

Anyone who has ever Googled (Binged?) about unit testing have heard about the “one assert per test rule”. The idea is that every unit test should have only one reason to fail. It’s a good rule that helps me write good, robust unit tests — but like all such rules of thumb it’s not always right (just most of the time).

If you’ve been using unit tests for some time you might have come to a conclusion that using multiple asserts is not always a bad idea — in fact for some tests it’s the only way to go…

Consider the following class:

public class SomeClass
{
    public int MyInt { get; set; }
    public string MyString { get; set; }
}

And now imagine a test in which that SomeClass is the result of your unit tests – what assert would you write?

[TestMethod]
public void CompareTwoAsserts()
{
    var actual = new SomeClass { MyInt = 1, MyString = "str-1" };

    Assert.AreEqual(1, actual.MyInt);
    Assert.AreEqual("str-1", actual.MyString);
}

Using two asserts would work, at least for a time. The problem is that failing the first assert would cause an exception to be thrown leaving us with no idea if the second would have passed or failed.

We can solve this issue by splitting the test into two tests — one test per assert. This seems like overkill in this case - we’re not asserting for two different, unrelated “things”. We’re in fact testing one SomeClass that happen to have two properties.

Ideally I would have liked to write the following test: 

[TestMethod]
public void CompareTwoObjects()
{
    var actual = new SomeClass {MyInt = 1,MyString = "str-1"};
    var expected = new SomeClass {MyInt = 1,MyString = "str-1"};

    Assert.AreEqual(expected, actual);
}

Unfortunately it would fail. The reason is that deep down inside our assert have no idea what is an “equal” object and so it runs Object.Equals and throws an exception in case of failure. Since the default behavior of Equals is to compare references (in case of classes) the result is a fail.

Due to this behavior there are many (myself included) who suggest overriding Equals to make sure that the actual values are compared, which could be a problem if our production code cannot be changed to accommodate our tests. There are ways around this limitation, such as using a Helper class (ahem) that would do the heavy lifting by inheriting (or not) the original class and adding custom Equals code.

I propose another option – one that could be useful , especially when there’s a need to compare different properties in different tests.

Using Fake Objects to Compare Real Objects

In order to change the way two objects are compared in an assert we only need change the behavior of one of them – the expect value (might change depending on the unit testing framework). And who is better in changing behavior of objects in tests than your friendly-neighborhood mocking framework?

And so using FakeItEasy I was able to create the following code:

[TestMethod]
public void CompareOnePropertyInTwoObjects()
{
    var actual = new SomeClass { MyInt = 1, MyString = "str-1" };
    var expected = new SomeClass { MyInt = 1, MyString = "str-1" };

    var fakeExpected = A.Fake<someclass>(o => o.Wrapping(expected));

    A.CallTo(() => fakeExpected.Equals(A<object>._)).ReturnsLazily(
        call =>
        {
            var other = call.GetArgument<someclass>(0);

            return expected.MyInt == other.MyInt;
        });

    Assert.AreEqual(fakeExpected, actual);
}

What we have here is a new fake object a.k.a fakeExpected which would call custom code when its Equals method is called.

The new Equals would return true if MyInt is the same in the two objects. I’ve also created the new fake using Wrapping so that the original methods on the class would still be called – I really care about ToString which I would override to produce a meaningful assertion message.

Now all I needed to do is to compare the fakeExpected with the actual result from the test.

In a similar way I’ve created a new extension method that would compare the properties on two classes:

public static T ByProperties<T>(this T expected)
{
    var fakeExpected = A.Fake<T>(o => o.Wrapping(expected));

    var properties = expected.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);

    A.CallTo(() => fakeExpected.Equals(A<object>._)).ReturnsLazily(
        call =>
        {
            var actual = call.GetArgument<object>(0);

            if (ReferenceEquals(null, actual))
                return false;
            if (ReferenceEquals(expected, actual))
                return true;
            if (actual.GetType() != expected.GetType())
                return false;

            return AreEqualByProperties(expected, actual, properties);
        });

    return fakeExpected;
}

private static bool AreEqualByProperties(object expected, object actual, PropertyInfo[] properties)
{
    foreach (var propertyInfo in properties)
    {
        var expectedValue = propertyInfo.GetValue(expected);
        var actualValue = propertyInfo.GetValue(actual);

        if (expectedValue == null || actualValue == null)
        {
            if (expectedValue != null || actualValue != null)
            {
                return false;
            }
        }
        else if (typeof (System.Collections.IList).IsAssignableFrom(propertyInfo.PropertyType))
        {
            if (!AssertListsEquals((IList) expectedValue, (IList) actualValue))
            {
                return false;
            }   
        }
        else if (!expectedValue.Equals(actualValue))
        {
            return false;
        }
    }

    return true;
}

private static bool AssertListsEquals(IList expectedValue, IList actualValue)
{
    if (expectedValue.Count != actualValue.Count)
    {
        return false;
    }

    for (int I = 0; I < expectedValue.Count; I++)
    {
        if (!Equals(expectedValue[I], actualValue[I]))
        {
            return false;
        }
    }

    return true;
}

And now I can use the following to compare my expected value with the value returned by the test:

[TestMethod]
public void CompareTwoObjectsByProperties()
{
    var actual = new SomeClass { MyInt = 1, MyString = "str-1" };
    var expected = new SomeClass { MyInt = 1, MyString = "str-1" };

    Assert.AreEqual(expected.ByProperties(), actual);
}

Simple(ish) is it? I prefer this method since I no longer need to make changes to my production code (e.g. SomeClass) but I can still use a plain vanilla unit testing framework.

What do you think?

unit test Object (computer science)

Published at DZone with permission of Dror Helper, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • TDD Typescript NestJS API Layers with Jest Part 1: Controller Unit Test
  • Chaos Mesh — A Solution for System Resiliency on Kubernetes
  • Clean Unit Testing
  • The Anatomy of Good Unit Testing

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!