簡體   English   中英

NullReference異常,即使列表項不為空

[英]NullReference exception even though list items are not null

我必須在這里丟失一些東西,但是我似乎有一個List,即使我已經檢查並確認不是,它們的項目也被捕獲為null

我對ASP.NET MVC項目的單元測試在foreach循環上引發了NullReferenceException ,但是我找不到任何原因,因此我在代碼中進行了一些檢查。 令我驚訝的是,check語句沒有捕獲任何空值,但是異常仍然存在。 以下是相關代碼:

[HttpPost]
[ValidateAntiForgeryToken]
public PartialViewResult CreateSimilar(int rebateId, List<AddressInput> addresses, bool recdResults = false)
{
    List<RebateHeader> newRebates = new List<RebateHeader>();
    RebateHeader entity = null;

    int newId = -1;

    if (!recdResults)
    {
        var repo = _db as HeaderRepository;
        List<PotentialDuplicate> allDups = new List<PotentialDuplicate>();

        //A few checks for null objects to illustrate my point-------
        if (addresses == null)
            throw new ApplicationException("Addresses was null"); //Not thrown
        else
            System.Console.WriteLine("Addresses was not null"); //This line is hit

        foreach (AddressInput address in addresses)
        {
            if (address == null)
                throw new ApplicationException("Address was null"); //Not thrown
            else
                System.Console.WriteLine("Address was not null"); //This line is hit
        }

        var test = addresses[0];
        System.Console.WriteLine(test.City); //This line returns a value
        System.Console.WriteLine(test.State); //This line returns a value
        //End checks---------------------------------------------------

        foreach (AddressInput address in addresses) //NullReferenceException THROWN HERE
        {
            List<PotentialDuplicate> dups = repo.GetDuplicateAddresses(
                address.Address, address.City, address.State).ToList();
            if (dups.Count > 0)
            {
                allDups.AddRange(dups);
            }
        }

        if (allDups.Count > 0)
        {
            return PartialView("_AddressDialogPotentialDup", allDups);
        }
    }
    . . . //Additional code truncated
    return PartialView("_IndexNoPager", model);
}

我必須在這里丟失一些東西,但是我沒有看到它。 有任何想法嗎?

作為進一步的參考,這是失敗的單元測試:

[Test]
public void CreateSimilar_Adds_1_New_Record()
{
    EntryController controller = new EntryController(repository);
    List<AddressInput> addresses = new List<AddressInput> 
    {   
        new AddressInput 
    { 
        Address = "Duplicate St.", City = "Testville", State = "MN", 
        ClosingDate = null, Quarter = "115" 
    }
    };

    controller.CreateSimilar(1, addresses); //Unit test FAILS HERE

    Assert.AreEqual(4, repository.GetAll().Count());
    Assert.AreEqual(1, repository.Added.Count);
    Assert.AreEqual("Test Duplicate 1", repository.Added[0].Address);
}

更新:為響應下面的評論,這是我的GetDuplicateAddresses代碼:

public IEnumerable<PotentialDuplicate> GetDuplicateAddresses(
    string address, string city, string state)
{
    var result = new List<PotentialDuplicate>();

    using (SqlCommand cmd = new SqlCommand("dbo.GetDuplicateAddresses", (SqlConnection)this.Database.Connection))
    {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@Address", address);
        cmd.Parameters.AddWithValue("@City", city);
        cmd.Parameters.AddWithValue("@State", state);

        cmd.Connection.Open();
        using (var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
        {
            while (reader.Read())
            {
                result.Add(new PotentialDuplicate
                {
                    OrigAddress = address,
                    RebateIdMatch = reader.GetInt32(0),
                    Address = reader.GetString(1),
                    MatchType = reader.GetString(2)
                });
            }

            return result;
        }
    }
}

這是我在單元測試中使用的存根:

public IEnumerable<PotentialDuplicate> GetDuplicateAddresses(
    string address, string city, string state)
{
    var result = new List<PotentialDuplicate>();
    return result;
}

在做dups.Count()> 0之前,我將檢查“ dups”是否為空。

事實證明,問題出在這個演員上:

var repo = _db as HeaderRepository;

我必須重構一些其他代碼,並且如果將來有類似的問題,我會稍稍更改此行以引發InvalidCastException

var repo = (IHeaderRepository)_db;

我什至沒有想到要檢查這一點,因為編譯器將foreach循環突出顯示為異常的位置。 感謝Tim Southard和thepirat000指出循環內的代碼塊可能導致編譯器引發異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM