[英]Stepping through and debugging code in Unit tests
我無法調試或單步執行單元測試。
這是我的示例測試代碼...
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using DomainModel.Entities;
using DomainModel.Abstract;
using WebUI.Controllers;
namespace Tests
{
[TestClass]
public class PeopleControllerTests
{
static IPeopleRepository MockPeopleRepository(params Person[] people)
{
var mockPeopleRepos = new Moq.Mock<IPeopleRepository>();
mockPeopleRepos.Setup(x => x.People).Returns(people.AsQueryable());
return mockPeopleRepos.Object;
}
[TestMethod]
public void Count_Of_People()
{
IPeopleRepository repository = MockPeopleRepository(
new Person { Age = 31, Gender = "Male", Name = "Tom" },
new Person { Age = 25, Gender = "Female", Name = "Sally" },
new Person { Age = 18, Gender = "Female", Name = "John" }
);
PeopleController controller = new PeopleController(repository);
var people = controller.List().ViewData.Model;
var peoplelist = people as IList<Person>;
Assert.AreEqual(3, peoplelist.Count);
}
}
}
使用 Microsoft.VisualStudio.TestTools.UnitTesting 時,轉到 VS 2010 主菜單中的“測試”,單擊子菜單“調試”->“當前上下文中的測試”。
右鍵單擊測試代碼並選擇“運行測試”將永遠不會啟動調試器,即使在 mode = debug 時也不行。
可以,謝謝:)
不過,要真正打破它們,您需要在調試模式下運行單元測試。
另一個解決方案...
您需要運行並附加調試器。
將此行設置在測試中執行的第一行(可能在測試類構造函數中):
System.Diagnostics.Debugger.Launch();
然后當調試窗口打開時,選擇 Visual Studio。
如果您正在運行 NUnit,那就太簡單了:
也許簡單地調試測試和設置斷點在某些類型的單元測試中起作用,但如果您調試,例如 Web 服務,則不起作用。
要調試 Web 服務(在單元測試中中斷),您必須插入以下代碼:
System.Diagnostics.Debugger.Break();
這將顯示一個彈出窗口,說明應用程序停止工作,您可以選擇調試它。
更多信息: http : //msdn.microsoft.com/en-us/library/ms243172.aspx#DebuggingOnCassini
一種選擇是安裝TestDriven.net ,這樣可以更輕松地在任何主要的單元測試 .NET 框架( NUnit 、 xUnit 、 Visual Studio 工具等)上運行單元測試。
安裝后,您可以右鍵單擊一個函數並選擇Test With → debugger 。
在 Visual Studio 中調試單元測試的兩個簡單步驟:
單步執行單元測試與我們在 Visual Studio 中單步執行任何其他代碼的方式非常相似。
您還可以從測試資源管理器窗口調試單元測試
調試所有測試 單擊測試 - 調試 - 所有測試 然后執行將在所有單元測試中的所有斷點處暫停
要記住的一件事是,如果您在 Visual Studio 中選擇運行測試而不是調試測試,單元測試中的斷點將被忽略。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.