В чем разница между Assert.AreEqual и Assert.Equals C#?
Assert — это обычный класс, который, как и все классы .NET, наследуют от System.Object . Assert.Equals – это просто наследуемый метод Object.Equals .
Asser.AreEquals – это метод класса Assert , который выкидывает AssertFailedException если два объекта не равны. Это штатный способ проверять утверждение о равенстве двух объектов.
В версии TestFramework 14.0.0.X Assert.Equals перекрыт, и выкидывает исключение, что бы избежать путаницы и не вводить никого в заблуждение. Внутри написано что-то такое:
/// Static equals overloads are used for comparing instances of two types for reference /// equality. This method should not be used for comparison of two instances for /// equality. This object will always throw with Assert.Fail. Please use /// Assert.AreEqual and associated overloads in your unit tests. public new static bool Equals(object objA, object objB)
Использование классов Assert для модульного тестирования
Область применения:
Visual Studio Visual Studio для Mac
Visual Studio Code ![]()
Классы Assert пространства имен Microsoft.VisualStudio.TestTools.UnitTesting служат для проверки определенных функциональных возможностей. Метод модульного теста использует код метода в коде приложения, но сообщает о корректности поведения кода только в том случае, если включены операторы Assert.
Типы классов Assert
В пространстве имен Microsoft.VisualStudio.TestTools.UnitTesting имеется несколько типов классов Assert.
В методе теста можно вызывать любые методы класса Microsoft.VisualStudio.TestTools.UnitTesting.Assert, например Assert.AreEqual. Класс Assert содержит много методов для выбора, и многие из этих методов имеют несколько перегрузок.
Сравнение строк и коллекций
Класс CollectionAssert используется для сравнения коллекций объектов и проверки состояния коллекции.
Класс StringAssert используется для сравнения и проверки строк. Этот класс содержит ряд полезных методов, таких как StringAssert.Contains, StringAssert.Matches и StringAssert.StartsWith.
Исключения
Исключение AssertFailedException возникает в случае неудачного завершения теста. Причиной неудачного завершения теста может быть истечение времени ожидания, непредвиденное исключение или оператор Assert, создающий результат Сбой.
Исключение AssertInconclusiveException возникает при каждом тесте с неопределенным результатом. Как правило, оператор Assert.Inconclusive добавляется к тесту, над которым еще ведется работа, для обозначения его неготовности к выполнению.
В качестве альтернативы можно пометить тест, который еще не готов к выполнению, атрибутом IgnoreAttribute. Однако в этом случае будет невозможным легко создать отчет по числу тестов, которые еще не реализованы.
При написании нового класса исключения Assert наследование от базового класса UnitTestAssertException упрощает идентификацию исключения как ошибки подтверждения, а не непредвиденного исключения, выдаваемого тестом или рабочим кодом.
Чтобы проверить, действительно ли вызывается исключение, которое должно вызываться методом в коде приложения, используйте метод Assert.ThrowsException.
См. также
Assert. Are Equal Method
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Overloads
Tests whether the specified objects are equal and throws an exception if the two objects are not equal. Different numeric types are treated as unequal even if the logical values are equal. 42L is not equal to 42.
Tests whether the specified strings are equal and throws an exception if they are not equal.
Tests whether the specified strings are equal and throws an exception if they are not equal. The invariant culture is used for the comparison.
Tests whether the specified floats are equal and throws an exception if they are not equal.
Tests whether the specified doubles are equal and throws an exception if they are not equal.
Tests whether the specified strings are equal and throws an exception if they are not equal. The invariant culture is used for the comparison.
Tests whether the specified strings are equal and throws an exception if they are not equal.
Tests whether the specified strings are equal and throws an exception if they are not equal.
Tests whether the specified objects are equal and throws an exception if the two objects are not equal. Different numeric types are treated as unequal even if the logical values are equal. 42L is not equal to 42.
Tests whether the specified doubles are equal and throws an exception if they are not equal.
Tests whether the specified strings are equal and throws an exception if they are not equal. The invariant culture is used for the comparison.
Tests whether the specified floats are equal and throws an exception if they are not equal.
Tests whether the specified objects are equal and throws an exception if the two objects are not equal. Different numeric types are treated as unequal even if the logical values are equal. 42L is not equal to 42.
Tests whether the specified doubles are equal and throws an exception if they are not equal.
Tests whether the specified floats are equal and throws an exception if they are not equal.
Tests whether the specified values are equal and throws an exception if the two values are not equal. Different numeric types are treated as unequal even if the logical values are equal. 42L is not equal to 42.
Tests whether the specified values are equal and throws an exception if the two values are not equal. Different numeric types are treated as unequal even if the logical values are equal. 42L is not equal to 42.
Tests whether the specified values are equal and throws an exception if the two values are not equal. Different numeric types are treated as unequal even if the logical values are equal. 42L is not equal to 42.
AreEqual(Object, Object)
Tests whether the specified objects are equal and throws an exception if the two objects are not equal. Different numeric types are treated as unequal even if the logical values are equal. 42L is not equal to 42.
public: static void AreEqual(System::Object ^ expected, System::Object ^ actual);
public static void AreEqual (object expected, object actual);
static member AreEqual : obj * obj -> unit
Public Shared Sub AreEqual (expected As Object, actual As Object)
Parameters
The first object to compare. This is the object the tests expects.
The second object to compare. This is the object produced by the code under test.
Exceptions
Thrown if expected is not equal to actual .
Applies to
AreEqual(String, String, Boolean, CultureInfo, String, Object[])
Tests whether the specified strings are equal and throws an exception if they are not equal.
public: static void AreEqual(System::String ^ expected, System::String ^ actual, bool ignoreCase, System::Globalization::CultureInfo ^ culture, System::String ^ message, . cli::array ^ parameters);
public static void AreEqual (string expected, string actual, bool ignoreCase, System.Globalization.CultureInfo culture, string message, params object[] parameters);
static member AreEqual : string * string * bool * System.Globalization.CultureInfo * string * obj[] -> unit
Public Shared Sub AreEqual (expected As String, actual As String, ignoreCase As Boolean, culture As CultureInfo, message As String, ParamArray parameters As Object())
Parameters
The first string to compare. This is the string the tests expects.
The second string to compare. This is the string produced by the code under test.
ignoreCase Boolean
A Boolean indicating a case-sensitive or insensitive comparison. (true indicates a case-insensitive comparison.)
A CultureInfo object that supplies culture-specific comparison information.
The message to include in the exception when actual is not equal to expected . The message is shown in test results.
parameters Object[]
An array of parameters to use when formatting message .
Exceptions
Thrown if expected is not equal to actual .
Applies to
AreEqual(String, String, Boolean, String, Object[])
Tests whether the specified strings are equal and throws an exception if they are not equal. The invariant culture is used for the comparison.
public: static void AreEqual(System::String ^ expected, System::String ^ actual, bool ignoreCase, System::String ^ message, . cli::array ^ parameters);
public static void AreEqual (string expected, string actual, bool ignoreCase, string message, params object[] parameters);
static member AreEqual : string * string * bool * string * obj[] -> unit
Public Shared Sub AreEqual (expected As String, actual As String, ignoreCase As Boolean, message As String, ParamArray parameters As Object())
Parameters
The first string to compare. This is the string the tests expects.
The second string to compare. This is the string produced by the code under test.
ignoreCase Boolean
A Boolean indicating a case-sensitive or insensitive comparison. (true indicates a case-insensitive comparison.)
The message to include in the exception when actual is not equal to expected . The message is shown in test results.
parameters Object[]
An array of parameters to use when formatting message .
Exceptions
Thrown if expected is not equal to actual .
Applies to
AreEqual(Single, Single, Single, String, Object[])
Tests whether the specified floats are equal and throws an exception if they are not equal.
public: static void AreEqual(float expected, float actual, float delta, System::String ^ message, . cli::array ^ parameters);
public static void AreEqual (float expected, float actual, float delta, string message, params object[] parameters);
static member AreEqual : single * single * single * string * obj[] -> unit
Public Shared Sub AreEqual (expected As Single, actual As Single, delta As Single, message As String, ParamArray parameters As Object())
Parameters
The first float to compare. This is the float the tests expects.
The second float to compare. This is the float produced by the code under test.
The required accuracy. An exception will be thrown only if actual is different than expected by more than delta .
The message to include in the exception when actual is different than expected by more than delta . The message is shown in test results.
parameters Object[]
An array of parameters to use when formatting message .
Exceptions
Thrown if expected is not equal to actual .
Applies to
AreEqual(Double, Double, Double, String, Object[])
Tests whether the specified doubles are equal and throws an exception if they are not equal.
public: static void AreEqual(double expected, double actual, double delta, System::String ^ message, . cli::array ^ parameters);
public static void AreEqual (double expected, double actual, double delta, string message, params object[] parameters);
static member AreEqual : double * double * double * string * obj[] -> unit
Public Shared Sub AreEqual (expected As Double, actual As Double, delta As Double, message As String, ParamArray parameters As Object())
Parameters
The first double to compare. This is the double the tests expects.
The second double to compare. This is the double produced by the code under test.
The required accuracy. An exception will be thrown only if actual is different than expected by more than delta .
The message to include in the exception when actual is different than expected by more than delta . The message is shown in test results.
parameters Object[]
An array of parameters to use when formatting message .
Exceptions
Thrown if expected is not equal to actual .
Applies to
AreEqual(String, String, Boolean, String)
Tests whether the specified strings are equal and throws an exception if they are not equal. The invariant culture is used for the comparison.
public: static void AreEqual(System::String ^ expected, System::String ^ actual, bool ignoreCase, System::String ^ message);
public static void AreEqual (string expected, string actual, bool ignoreCase, string message);
static member AreEqual : string * string * bool * string -> unit
Public Shared Sub AreEqual (expected As String, actual As String, ignoreCase As Boolean, message As String)
Parameters
The first string to compare. This is the string the tests expects.
The second string to compare. This is the string produced by the code under test.
ignoreCase Boolean
A Boolean indicating a case-sensitive or insensitive comparison. (true indicates a case-insensitive comparison.)
The message to include in the exception when actual is not equal to expected . The message is shown in test results.
Exceptions
Thrown if expected is not equal to actual .
Applies to
AreEqual(String, String, Boolean, CultureInfo)
Tests whether the specified strings are equal and throws an exception if they are not equal.
public: static void AreEqual(System::String ^ expected, System::String ^ actual, bool ignoreCase, System::Globalization::CultureInfo ^ culture);
public static void AreEqual (string expected, string actual, bool ignoreCase, System.Globalization.CultureInfo culture);
static member AreEqual : string * string * bool * System.Globalization.CultureInfo -> unit
Public Shared Sub AreEqual (expected As String, actual As String, ignoreCase As Boolean, culture As CultureInfo)
Parameters
The first string to compare. This is the string the tests expects.
The second string to compare. This is the string produced by the code under test.
ignoreCase Boolean
A Boolean indicating a case-sensitive or insensitive comparison. (true indicates a case-insensitive comparison.)
A CultureInfo object that supplies culture-specific comparison information.
Exceptions
Thrown if expected is not equal to actual .
Applies to
AreEqual(String, String, Boolean, CultureInfo, String)
Tests whether the specified strings are equal and throws an exception if they are not equal.
public: static void AreEqual(System::String ^ expected, System::String ^ actual, bool ignoreCase, System::Globalization::CultureInfo ^ culture, System::String ^ message);
public static void AreEqual (string expected, string actual, bool ignoreCase, System.Globalization.CultureInfo culture, string message);
static member AreEqual : string * string * bool * System.Globalization.CultureInfo * string -> unit
Public Shared Sub AreEqual (expected As String, actual As String, ignoreCase As Boolean, culture As CultureInfo, message As String)
Parameters
The first string to compare. This is the string the tests expects.
The second string to compare. This is the string produced by the code under test.
ignoreCase Boolean
A Boolean indicating a case-sensitive or insensitive comparison. (true indicates a case-insensitive comparison.)
A CultureInfo object that supplies culture-specific comparison information.
The message to include in the exception when actual is not equal to expected . The message is shown in test results.
Exceptions
Thrown if expected is not equal to actual .
Applies to
AreEqual(Object, Object, String, Object[])
Tests whether the specified objects are equal and throws an exception if the two objects are not equal. Different numeric types are treated as unequal even if the logical values are equal. 42L is not equal to 42.
public: static void AreEqual(System::Object ^ expected, System::Object ^ actual, System::String ^ message, . cli::array ^ parameters);
public static void AreEqual (object expected, object actual, string message, params object[] parameters);
static member AreEqual : obj * obj * string * obj[] -> unit
Public Shared Sub AreEqual (expected As Object, actual As Object, message As String, ParamArray parameters As Object())
Parameters
The first object to compare. This is the object the tests expects.
The second object to compare. This is the object produced by the code under test.
The message to include in the exception when actual is not equal to expected . The message is shown in test results.
parameters Object[]
An array of parameters to use when formatting message .
Exceptions
Thrown if expected is not equal to actual .
Applies to
AreEqual(Double, Double, Double, String)
Tests whether the specified doubles are equal and throws an exception if they are not equal.
public: static void AreEqual(double expected, double actual, double delta, System::String ^ message);
public static void AreEqual (double expected, double actual, double delta, string message);
static member AreEqual : double * double * double * string -> unit
Public Shared Sub AreEqual (expected As Double, actual As Double, delta As Double, message As String)
Parameters
The first double to compare. This is the double the tests expects.
The second double to compare. This is the double produced by the code under test.
The required accuracy. An exception will be thrown only if actual is different than expected by more than delta .
The message to include in the exception when actual is different than expected by more than delta . The message is shown in test results.
Exceptions
Thrown if expected is not equal to actual .
Applies to
AreEqual(String, String, Boolean)
Tests whether the specified strings are equal and throws an exception if they are not equal. The invariant culture is used for the comparison.
public: static void AreEqual(System::String ^ expected, System::String ^ actual, bool ignoreCase);
public static void AreEqual (string expected, string actual, bool ignoreCase);
static member AreEqual : string * string * bool -> unit
Public Shared Sub AreEqual (expected As String, actual As String, ignoreCase As Boolean)
Parameters
The first string to compare. This is the string the tests expects.
The second string to compare. This is the string produced by the code under test.
ignoreCase Boolean
A Boolean indicating a case-sensitive or insensitive comparison. (true indicates a case-insensitive comparison.)
Exceptions
Thrown if expected is not equal to actual .
Assert areequal c что это
Данное руководство устарело. Актуальное руководство: Руководство по ASP.NET Core
Последнее обновление: 31.10.2015
Возьмем тот же проект из прошлый темы (либо создадим новый) и добавим в главный проект веб-приложения в папку Contollers новый контроллер StoreController:
public class StoreController : Controller < public ActionResult Index() < ViewBag.Message = "Hello world!"; return View(); >>
Контроллер имеет только один метод, который устанавливает свойство ViewBag.Message и генерирует объект ActionResult. А также добавим для метода Index представление.
Теперь перейдем к проекту тестов и добавим в него новый класс тестов. Для этого мы можем добавить либо стандартный класс, либо использовать специальный шаблон файлов. Для этого в проекте тестов нажмем правой кнопкой мыши на каталог Controllers и в появившемся контекстном меню выберем Add->Unit Test. :

По умолчанию добавляет класс UnitTest1. Во-первых, изменим название класса и файла на StoreControllerTest . Затем изменим следующим образом сам класс:
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using UnitTestApp.Controllers; using System.Web.Mvc; namespace UnitTestApp.Tests.Controllers < [TestClass] public class StoreControllerTest < [TestMethod] public void IndexViewResultNotNull() < StoreController controller = new StoreController(); ViewResult result = controller.Index() as ViewResult; Assert.IsNotNull(result); >[TestMethod] public void IndexViewEqualIndexCshtml() < StoreController controller = new StoreController(); ViewResult result = controller.Index() as ViewResult; Assert.AreEqual("Index", result.ViewName); >[TestMethod] public void IndexStringInViewbag() < StoreController controller = new StoreController(); ViewResult result = controller.Index() as ViewResult; Assert.AreEqual("Hello world!", result.ViewBag.Message); >> >
Метод IndexViewResultNotNull тестирует результат метода — возвращаемый объект ViewResult не должен иметь значение null. Метод IndexViewEqualIndexCshtml проверяет название вызываемого представления с помощью вызова Assert.AreEqual . А метод IndexStringInViewbag проверяет значение строки в свойстве ViewBag.Message.
Хотя у нас только один метод в контроллере, для него мы создали три тестовых метода для теста каждого отдельного тестового действия. Подобная изоляция облегчает тестирования отдельных участков кода.
Перед запуском тестов перестроим главный проект. И запустим тесты. В этом случае мы увидим, что один тест не пройден — тот, который верифицирует представление:

Тест не пройден, потому что при вызове метода View нам надо явным образом указывать представление. Поэтому изменим метод Index в главном проекте следующим образом:
public ActionResult Index()
Снова запустим тесты. И теперь уже все тесты должны быть успешно пройдены.
Все три действия имеют одну и ту же секцию Arrange, и, возможно, было бы неплохо сразу установить все начальные настройки для всех методов. Для этого изменим в тестовом проекте класс StoreControllerTest следующим образом:
[TestClass] public class StoreControllerTest < private StoreController controller; private ViewResult result; [TestInitialize] public void SetupContext() < controller = new StoreController(); result = controller.Index() as ViewResult; >[TestMethod] public void IndexViewResultNotNull() < Assert.IsNotNull(result); >[TestMethod] public void IndexViewEqualIndexCshtml() < Assert.AreEqual("Index", result.ViewName); >[TestMethod] public void IndexStringInViewbag() < Assert.AreEqual("Hello world!", result.ViewBag.Message); >>
Атрибут TestInitialize позволяет задать метод, который выполняет начальную инициализацию для каждого отдельного теста. Благодаря этому код сокращен, а в тестовых методах оставлены только части Assert. Однако подобный подход надо принимать с осторожностью, так как он осложняет возможности по изменению кода. В данном случае общий контекст очень прост, но если при изменении методов будет изменяться и их контекст, то придется вносить большие изменения во всех классах тестов, а не только в отдельный метод для тестов.
Класс Assert и тестирование результата
Класс Assert из пространства имен Microsoft.VisualStudio.TestTools.UnitTesting с помощью своих статических методов позволяет верифицировать результат выполнения некоторого действия. Ранее уже было рассмотрено несколько методов, в частности, метод Assert.IsNotNull() , проверяющий, не равен ли некоторый объект значению null. Кроме того, при тестировании нам доступен еще ряд методов:
- AreEqual(object expected, object actual) : проверяет, равны ли оба объекта. Имеет различные перегруженные версии, позволяющие сравнивать различные типы объектов
- AreEqual(T expected, T actual) : обобщенная версия предыдущего метода. Например, Assert.AreEqual(«Index», result.MasterName)
- AreNotEqual(object expected, object actual) : проверяет, не равны ли оба объекта. Тест проходит успешно, если объекты не равны
- AreNotEqual(T expected, T actual) : обобщенная версия предыдущего метода
- AreSame(object expected, object actual) : проверяет, указывают ли оба объекта на один и тот же объект в памяти
- AreNotSame(object expected, object actual) : проверяет, указывают ли оба объекта на разные объекты в памяти. Если они указывают на один и тот же объект, то тест заканчивается неудачно
- Equals(object objA, object objB) : проверяет на равенство оба объекта
- IsFalse(bool condition) : проверяет, равно ли условие condition значению false
- IsTrue(bool condition) : проверяет, равно ли условие condition значению true
- IsNull(object value) : проверяет, имеет ли объект value значение null
- IsInstanceOfType(object value, Type expectedType) : проверяет, представляет ли объект value тип expectedType
Используя эти методы, мы можем проверить различные ситуации в своем приложении.