Explicit conversion from int & # 8594; sbyte & # 8594; sbyte?

Given this piece of code

[TestMethod]
public void SByte()
{
 int integerValue = -129;
 sbyte sbyteValueFromInt = (sbyte) integerValue;
 Assert.AreEqual(sbyteValueFromInt, 127); // True

 byte byteValue = (byte) integerValue;
 sbyte sbyteValueFromByte= (sbyte) byteValue;
 Assert.AreEqual(sbyteValueFromByte, 127); // True 

 sbyte? nullableSbyte = sbyteValueFromByte;
 Assert.AreEqual(nullableSbyte.Value, 127); // True
 Assert.AreEqual((sbyte)nullableSbyte, 127); // True
 Assert.AreEqual(nullableSbyte, 127); // Assert.AreEqual failed. Expected:<127 (System.SByte)>. Actual:<127 (System.Int32)>. 
}

Why did the last statement fail?

If we dig into AreEqual<object>of MSTest, then shouldn't it be recognized 127to convert to sbyte??

Assert.AreEqual<object>(expected, actual, message, parameters);

public static void AreEqual<T>(T expected, T actual, string message, params object[] parameters)
{
 message = Assert.CreateCompleteMessage(message, parameters);
 if (object.Equals((object) expected, (object) actual))
  return;
 Assert.HandleFailure ...
}

Why didn’t he know how to drop 127before sbyte, but did he do it with sbyte??

+4
source share
1 answer

This is apparently a function mistakeMSTest. When you repeat the test with NUnitor simply with, an operator ==implicit conversion is performed.

MSTest Assert boils down to:

Assert.AreEqual<object>(expected, actual, message, parameters);

public static void AreEqual<T>(T expected, T actual, string message, params object[] parameters)
{
  message = Assert.CreateCompleteMessage(message, parameters);
  if (object.Equals((object) expected, (object) actual))
    return;
  Assert.HandleFailure ...
}

Premature boxing through objectis most likely the culprit.

, MSTest T, :

Assert.AreEqual<sbyte?>(nullableSbyte, 127);

.

, NUnit Assert - :

    [Test]
    public void SByte()
    {
        sbyte? nullableSbyte = sbyteValueFromByte;
        Assert.AreEqual(nullableSbyte.Value, 127); // True
        Assert.AreEqual(nullableSbyte, 127);
    }

unit test:

    sbyte? nullableSbyte = sbyteValueFromByte;
    if (nullableSbyte.Value != 127)
    {
        throw new Exception("Not Equal");
    }
    if (nullableSbyte != 127)
    {
        throw new Exception("Not Equal");
    }

Edit

R # comparison

+2

Source: https://habr.com/ru/post/1532403/


All Articles