2015-05-26 3 views
1

Итак, я тестирую устройство, и я получил вышеуказанное сообщение. Я осмотрелся и не могу найти ответ на мою проблему. Я без понятия что это значит. Могут ли быть два разных типа Null? Спасибо за помощь!Ожидаемое подтверждение: <Null> Актуально: <(null)>

//This is invalid input given to the CategoryList constructor. It returns a null value.  
//The message i get is: Assert.AreEqual failed. Expected:<Null>.Actual:<(null)>. 

CategoryList test = new CategoryList(
    Primitives.ConstantPrimitives.ConnectionString, 
    Primitives.ConstantPrimitives.negativeShort, 
    false); 
Assert.AreEqual(test.Cat_ID, null); 

Вот CategoryList

using System; 
using System.Collections.Generic; 
using System.Data.SqlClient; 
using System.Data.SqlTypes; 

namespace Retail_Utilities.Util.DataClasses 
{ 
    public class CategoryList 
    { 
     public SqlInt16 Cat_ID { get; set; } 
     public String Cat { get; set; } 
     public Boolean Active_YN { get; set; } 
     public SqlDateTime Last_Update { get; set; } 
     public Int16 Parent_Cat_ID { get; set; } 
     public Int16? Top_Level_Cat_ID { get; set; } 
     public Int16? Pallet_Type_ID { get; set; } 
     public CategoryList ParentCat { get; set; } 

     public bool IsChild { get; set; } 

     public CategoryList() 
     { 
      IsChild = false; 
     } 

     public CategoryList(string connectionString, Int16 catID, Boolean isChild = false) 
     { 
      IsChild = false; 

      using (SqlConnection connection = new SqlConnection(connectionString)) 
      { 
       SqlCommand command = connection.CreateCommand(); 
       string sqlCommand = "SELECT TOP 1 Cat_ID, Cat, Active_YN, Last_Update, Parent_Cat_ID, Top_Level_Cat_ID, Pallet_Type_ID, Deactivated_On"; 
       sqlCommand += " FROM Twr_List_Cat WHERE 0=0"; 
       sqlCommand += " AND Cat_ID = " + catID; 
       command.CommandText = sqlCommand; 
       connection.Open(); 
       SqlDataReader reader = command.ExecuteReader(); 
       if (reader.HasRows) 
       { 
        while (reader.Read()) 
        { 
         IsChild = isChild; 
         Cat_ID = reader.GetSqlInt16(0); 
         Cat = reader.GetString(1); 
         Active_YN = reader.GetBoolean(2); 
         Last_Update = reader.GetSqlDateTime(3); 
         Parent_Cat_ID = reader.GetInt16(4); 
         Top_Level_Cat_ID = reader.IsDBNull(5) ? null : (Int16?)reader.GetInt16(5); 
         Pallet_Type_ID = reader.IsDBNull(6) ? null : (Int16?)reader.GetInt16(6); 
         if (!IsChild) { ParentCat = new CategoryList(connectionString, Parent_Cat_ID, true); } 
        } 
       } 
       reader.Close(); 
      } 
     } 

     public static List<CategoryList> ListActiveCategories(string connectionString) 
     { 
      List<CategoryList> activeCats = new List<CategoryList>(); 
      using (SqlConnection connection = new SqlConnection(connectionString)) 
      { 
       using (SqlCommand command = connection.CreateCommand()) 
       { 
        command.CommandText = "SELECT Cat_ID, Cat, Active_YN, Last_Update, Parent_Cat_ID, Top_Level_Cat_ID, Pallet_Type_ID"; 
        command.CommandText += " FROM Twr_List_Cat"; 
        command.CommandText += " WHERE Active_YN = 1;"; 
        connection.Open(); 
        SqlDataReader reader = command.ExecuteReader(); 
        if (reader.HasRows) 
        { 
         while (reader.Read()) 
         { 
          CategoryList activeCat = new CategoryList 
          { 
           Cat_ID = reader.GetSqlInt16(0), 
           Cat = reader.GetString(1), 
           Active_YN = reader.GetBoolean(2), 
           Last_Update = reader.GetSqlDateTime(3), 
           Parent_Cat_ID = reader.GetInt16(4), 
           Top_Level_Cat_ID = reader.IsDBNull(5) ? null : (Int16?)reader.GetInt16(5), 
           Pallet_Type_ID = reader.IsDBNull(6) ? null : (Int16?)reader.GetInt16(6), 
          }; 
          activeCat.ParentCat = new CategoryList(connectionString, activeCat.Parent_Cat_ID, true); 
          activeCats.Add(activeCat); 
         } 
        } 
       } 
      } 
      return activeCats; 
     } 
    } 
} 
+0

Что 'Cat_ID'? Это «короткий?» Тип? Что произойдет, если вы измените последнее значение «null» на «(short?) Null»? –

+0

Отладить модульный тест и проверить значение 'test.Cat_ID'. – juharr

+0

это действительно короткое. я изменил его на (short?) null, и он по-прежнему дал то же сообщение, что и раньше. – Shikumaru

ответ

1

Да, есть несколько типов "нуль" в .Net:

  • регулярных null
  • DBNull и не связанный с "ничего там еще" для таких баз данных, как у вас есть - SqlInt16
  • Обнуляемых типа без значения
  • Кроме любой типа не определяя его ToString напечатать что-то вроде null всякий раза, когда он хочет, и, возможно, определяя сравнения/.Equals для null вернуться true.

Похоже, что у вас есть SqlInt16 без значения на основании <(null)>.

Возможно, вы ищете IsNull свойство этого типа вместо:

Assert.IsTrue(test.Cat_ID.IsNull); 
+0

Я изменил его как Assert.AreEqual (test.Cat_ID, DBNull.Value.Equals (null)); , но теперь в сообщении говорится: Ожидаемое: . Фактическое: . Почему сообщение об ошибке будет изменено для test.Cat_ID? Извините! – Shikumaru

+0

@Shikumaru - 'SqlInt16.IsNull', вероятно, то, что вам нужно (добавлено в ответ тоже). –

+0

Я попробовал Assert.AreEqual (test.Cat_ID, SqlInt16.Null.IsNull); Я получаю сообщение Ожидаемое: . Фактическое: . Мне не удалось выполнить SqlInt16.IsNull. Второй ответ только на утверждение кота ID.IsNull также не удалось :( – Shikumaru

Смежные вопросы