2

Try to compare objects with single private field

Object like this:

public struct A
{
    private readonly byte[] bytes;

    public A(byte[] bytes)
    {
        this.bytes = bytes;
    }
}

Compare this way:

var a = new A(new byte[] { 1, 2, 3 });
var b = new A(new byte[] { 1, 2, 3 });
a.Should().BeEquivalentTo(b);

Result:

Message: Expected a to be 

A
{
}, but found 

A
{
}.

Сan I get a positive comparison without override Equals?

VoidName
  • 340
  • 2
  • 16
  • You shouldn't assert on private members. There should be a public member that exposes a change in behaviour when `bytes` is different. See https://stackoverflow.com/a/34586/247702 – user247702 May 13 '19 at 07:42
  • @Stijn , it seems that I have an ambiguous case, object `A` is unique id, and it's field of other object in my code. Sound weird, but in all by case i does't compare unique id with other unique ids (store it in database like byte array, get byte array via `MyUniqueId.GetByteArray()`). So it look like I will overload `Equals` only for tests, – VoidName May 13 '19 at 09:20
  • So `A` has a method `GetByteArray()`? If so, you should write a unit test for that method instead of implementing `Equals()` I think. – user247702 May 13 '19 at 09:25
  • Yes, `A` has a method `GetByteArray()`, but in my test I compare objects that contain `A`: `class B { public A Id {get;} ... }` – VoidName May 13 '19 at 09:39

1 Answers1

2

Since you're comparing structs, which is treated by FA as a type with value semantics, FA will use the compiler-generated Equals implementation. In this case, your structs contain two different instances of a byte[] array, so they will never match. Also, FA will never report or access the values of private fields. Why would it if you decided it to be private? And you didn't override ToString in any suitable way.

So the only way to make this work is to add a public or internal property, or to implement Equals correctly.

Jonas Nyrup
  • 2,376
  • 18
  • 25
Dennis Doomen
  • 8,368
  • 1
  • 32
  • 44
  • 2
    This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/22995842) – Towkir May 13 '19 at 08:38
  • 1
    Rephrased my solution. – Dennis Doomen May 13 '19 at 08:48