|
| 1 | +--- |
| 2 | +title: "Don't use 'Assert.AreSame' or 'Assert.AreNotSame' with value types" |
| 3 | +description: "Learn about code analysis rule MSTEST0038: Don't use 'Assert.AreSame' or 'Assert.AreNotSame' with value types" |
| 4 | +ms.date: 01/06/2025 |
| 5 | +f1_keywords: |
| 6 | +- MSTEST0038 |
| 7 | +- AvoidAssertAreSameWithValueTypesAnalyzer |
| 8 | +helpviewer_keywords: |
| 9 | +- AvoidAssertAreSameWithValueTypesAnalyzer |
| 10 | +- MSTEST0038 |
| 11 | +author: Youssef1313 |
| 12 | +ms.author: ygerges |
| 13 | +--- |
| 14 | +# MSTEST0038: Don't use 'Assert.AreSame' or 'Assert.AreNotSame' with value types |
| 15 | + |
| 16 | +| Property | Value | |
| 17 | +|-------------------------------------|------------------------------------------------------------------------| |
| 18 | +| **Rule ID** | MSTEST0038 | |
| 19 | +| **Title** | Don't use 'Assert.AreSame' or 'Assert.AreNotSame' with value types | |
| 20 | +| **Category** | Usage | |
| 21 | +| **Fix is breaking or non-breaking** | Non-breaking | |
| 22 | +| **Enabled by default** | Yes | |
| 23 | +| **Default severity** | Warning | |
| 24 | +| **Introduced in version** | 3.8.0 | |
| 25 | +| **Is there a code fix** | No | |
| 26 | + |
| 27 | +## Cause |
| 28 | + |
| 29 | +The use of <xref:Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreSame%2A?displayProperty=nameWithType> or <xref:Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreNotSame*?displayProperty=nameWithType> with one or both arguments being a value type. |
| 30 | + |
| 31 | +## Rule description |
| 32 | + |
| 33 | +<xref:Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreSame%2A?displayProperty=nameWithType> and <xref:Microsoft.VisualStudio.TestTools.UnitTesting.Assert.AreNotSame%2A?displayProperty=nameWithType> work by comparing the *reference* of the given `expected`/`notExpected` and actual arguments via `ReferenceEquals`. Hence, when you pass a value type, it is [boxed](../../../csharp/programming-guide/types/boxing-and-unboxing.md#boxing). |
| 34 | + |
| 35 | +If using `AreSame`, the assert will always fail. If using `AreNotSame`, the assert will always pass. |
| 36 | + |
| 37 | +For `AreSame`, the only case when the assert passes is if both arguments are nullable value types whose values are both null. In this case, it's clearer to have two separate `Assert.IsNull` calls. |
| 38 | + |
| 39 | +## How to fix violations |
| 40 | + |
| 41 | +Use `Assert.AreEqual` and `Assert.AreNotEqual` instead of `Assert.AreSame` and `Assert.AreNotSame`. |
| 42 | +If using `Assert.AreSame` and both arguments are nullable value types whose values are expected to be null, then two separate `Assert.IsNull` calls might be a better fit than `AreEqual`, depending on the intent of the test. |
| 43 | + |
| 44 | +## When to suppress warnings |
| 45 | + |
| 46 | +Do not suppress a warning from this rule. Ignoring this rule will result in an assertion that will always fail or always pass. |
0 commit comments