C#單元測試UnitTest(二)--web.config檔案引發的異常
阿新 • • 發佈:2019-02-20
說明:在實際的web專案中,測試的方法都是對資料庫產生操作的,然我們的資料庫連結一般放在web.config檔案中,
一個簡單的案例來模擬一下呼叫場景
1,首先我們在web.config檔案加入一個配置
<add key="awe" value="3.0.0.0" />
2,然後在一個mvc的controller裡面加入一個簡單的讀取操作
public JsonResult Test(string name,int id) { var awe = WebConfigurationManager.AppSettings.Get("awe").ToString(); return Json(new { Name=name, Id=id, awe =awe }); }
3,建立測試程式碼
using Microsoft.VisualStudio.TestTools.UnitTesting; using Unit.Controllers; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Unit.Controllers.Tests { [TestClass()] public class HomeControllerTests { [TestMethod()] public void IndexTest() { HomeController con = new HomeController(); var obj=con.Test("xiaoming", 1); Assert.IsNotNull(obj); } } }
4,執行,這時候會發現單元測試丟擲webconfig讀取賦值引發空指標異常
5,解決:把webconfig的內容按照正確格式複製到單元測試的app.config檔案裡面。