How to compare 2 Arrays with Assert.Equals?

4

I need to compare two arrays in Assert.Equals .

When I test the method on the race, it is correct but the test does not pass.

Code:

public void SeparaStringTest() {
 RecebeComando recebecomando = new RecebeComando();
 string[] StringSeparada = {
  "A",
  "A",
  "B"
 };

 Assert.Equals(recebecomando.SeparaString("AAB"), StringSeparada);
 Assert.Equals(recebecomando.SeparaString("A A B"), StringSeparada);
 Assert.Equals(recebecomando.SeparaString("A-A-B"), StringSeparada);
}

public string[] SeparaString(string palavra) {
 palavra = palavra.Replace("-", "");
 palavra = palavra.Replace(" ", "");

 var comando = new string[palavra.Length];

 for (int i = 0; i < comando.Length; i++) {
  comando[i] = palavra[i].ToString();
 }
 return comando;
}
    
asked by anonymous 16.03.2017 / 13:07

3 answers

6

The Assert.AreEqual command compares as a reference, so you can compare arrays or lists, you should use CollectionAssert.AreEqual

public void SeparaStringTest()
{
    RecebeComando recebecomando = new RecebeComando();
    string[] StringSeparada = { "A", "A", "B" };

    CollectionAssert.AreEqual(recebecomando.SeparaString("AAB"), StringSeparada);
    CollectionAssert.AreEqual(recebecomando.SeparaString("A A B"), StringSeparada);
    CollectionAssert.AreEqual(recebecomando.SeparaString("A-A-B"), StringSeparada);
}

See Microsoft documentation:

Assert.AreEqual: link

CollectionAssert.AreEqual: link

    
16.03.2017 / 13:32
5

First there is an error there, Assert.Equals has the same behavior as method Equals of object , that is, this method checks if two variables point to the same reference.

You probably want to use the Assert.AreEqual method, this will compare item by item of the arrays and check their values.

I also took advantage of and made a modification to make the SeparaString method a bit simpler.

public static string[] SeparaString(string palavra, char? separador)
{
    string[] comando;

    if(separador == null)
        comando = palavra.ToCharArray().Select(x => x.ToString()).ToArray();
    else
        comando = palavra.Split((char)separador);

    return comando;
}

The use would be

SeparaString("AAB", null);
SeparaString("AAB", '-');
SeparaString("AAB", ' ');
    
16.03.2017 / 13:31
0

I managed to solve, in fact I needed to change to Assert.AreEqual the test looked like this:

public void SeparaStringTest()
{
    RecebeComando recebecomando = new RecebeComando();           
    string[] retornoDoMétodo = recebecomando.SeparaString("AAB");
    Assert.AreEqual(retornoDoMétodo.Length, 3);
    Assert.AreEqual(retornoDoMétodo[0], "A");
    Assert.AreEqual(retornoDoMétodo[1], "A");
    Assert.AreEqual(retornoDoMétodo[2], "B");
}
    
16.03.2017 / 13:49