'How to test two objects in xunit using FluentAssertions
I have a Matrix class, and another class which is using that matrix changing it a little bit. I'd like to test both matrix, one from the matrix class and the other one which has been changed, so I can confirmed they're not the same.
Something like this.
[Fact]
public void MatrixFromMatrixIsntTheSameThanMatrixFromMineSweeper()
{
Matrix _matrix = new Matrix(4, 4);
MineSweeper mineSweeper = new MineSweeper(4, 4, 2);
mineSweeper.Matrix.Should().NotBe(_matrix);
}
The thing is that Be/NotBe seems is using the reference from the object, so always it returns false because they're not the same. I also have tried with NotBeSameAs, NotBeEquivalentTo.
These are the Matrix and MineSweeper class.
Matrix Class
public struct Coordinate
{
public int X;
public int Y;
public Coordinate(int x, int y)
=> (X, Y) = (x, y);
}
public class Matrix
{
private readonly int _M, _N;
private readonly Cell[,] _matrix;
private const char InitValue = '.';
public Matrix(int m, int n)
{
(_M, _N) = (m, n);
_matrix = new Cell[m, n];
Initialize();
}
private void Initialize()
{
for (int m = 0; m < _M; m++)
for (int n = 0; n < _N; n++)
_matrix[m, n] = new Cell(InitValue);
}
public Cell At(Coordinate coordinate)
=> _matrix[coordinate.X, coordinate.Y];
public void SetMine(Coordinate coordinate)
{
_matrix[coordinate.X, coordinate.Y] = new Cell('*');
}
}
MineSweeper Class
public class MineSweeper
{
private readonly int _m, _n, _numMines;
public Matrix Matrix { get; }
public MineSweeper(int m, int n, int numMines)
{
(_m, _n, _numMines) = (m, n, numMines);
Matrix = new Matrix(m, n);
SetMines();
}
private void SetMines()
{
HashSet<Coordinate> minesSet = new HashSet<Coordinate>();
Random rnd = new Random();
while (minesSet.Count != _numMines)
minesSet.Add(new Coordinate(rnd.Next(0, _m), rnd.Next(0, _n)));
foreach (Coordinate coordinate in minesSet)
Matrix.SetMine(coordinate);
}
}
Solution 1:[1]
Normally we recommend BeEquivalentTo, but since your Matrix class doesn't expose any public fields or properties, the only other option is what NPras suggested in option 2.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dennis Doomen |
