使用 Visual Studio for Mac 在 macOS 上建置完整的 .NET Core 解決方案Building a complete .NET Core solution on macOS using Visual Studio for Mac

Visual Studio for Mac 針對開發 .NET Core 應用程式,提供功能完整的整合式開發環境 (IDE)。Visual Studio for Mac provides a full-featured Integrated Development Environment (IDE) for developing .NET Core applications. 本主題會逐步引導您建置一個包含可重複使用之程式庫和單元測試的 .NET Core 解決方案。This topic walks you through building a .NET Core solution that includes a reusable library and unit testing.

本教學課程會示範如何建立能接受來自使用者的搜尋文字和文字字串、使用類別庫中的方法計算搜尋文字出現在字串中的次數,並將結果傳回給使用者的應用程式。This tutorial shows you how to create an application that accepts a search word and a string of text from the user, counts the number of times the search word appears in the string using a method in a class library, and returns the result to the user. 解決方案也包含類別庫的單元測試,作為單元測試概念的簡介。The solution also includes unit testing for the class library as an introduction to unit testing concepts. 如果您偏好使用完整範例來進行教學課程,請下載範例解決方案 (英文)If you prefer to proceed through the tutorial with a complete sample, download the sample solution. 如需下載指示,請參閱範例和教學課程For download instructions, see Samples and Tutorials.

注意

我們非常重視您的意見反應。Your feedback is highly valued. 您有兩種方式可以提供意見反應給 Visual Studio for Mac 開發小組:There are two ways you can provide feedback to the development team on Visual Studio for Mac:

  • 在 Visual Studio for Mac 中,從功能表選取 [說明] > [回報問題] ,或從歡迎畫面選取 [回報問題] ,這會開啟用來提出錯誤報告的視窗。In Visual Studio for Mac, select Help > Report a Problem from the menu or Report a Problem from the Welcome screen, which opens a window for filing a bug report. 您可在開發人員社群入口網站追蹤您的意見反應。You can track your feedback in the Developer Community portal.
  • 若要提出建議,請從功能表選取 [說明] > [提供建議] ,或從歡迎畫面選取 [提供建議] ,這會帶您前往 Visual Studio for Mac 開發人員社群網頁 (英文)。To make a suggestion, select Help > Provide a Suggestion from the menu or Provide a Suggestion from the Welcome screen, which takes you to the Visual Studio for Mac Developer Community webpage.

必要條件Prerequisites

如需必要條件的詳細資訊,請參閱 Mac 上 .NET Core 的先決條件For more information on prerequisites, see the Prerequisites for .NET Core on Mac. 如需 Visual Studio 2017 for Mac 的完整系統需求,請參閱 Visual Studio 2017 for Mac 產品系列系統需求For the full system requirements of Visual Studio 2017 for Mac, see Visual Studio 2017 for Mac Product Family System Requirements.

建置程式庫Building a library

  1. 選取歡迎畫面上的 [新增專案] 。On the Welcome screen, select New Project. 在 [新增專案] 對話方塊中的 [.NET Core] 節點下,選取 [.NET Standard 程式庫] 範本。In the New Project dialog under the .NET Core node, select the .NET Standard Library template. 這樣會建立 .NET Standard 程式庫,它會以 .NET Core 和支援 .NET Standard 2.0 版的任何其他 .NET 實作為目標。This creates a .NET Standard library that targets .NET Core as well as any other .NET implementation that supports version 2.0 of the .NET Standard. 選取 [下一步] 。Select Next.

    Visual Studio for Mac [新增專案] 對話方塊

  2. 將專案命名為 "TextUtils" (「文字公用程式」的簡短名稱),並將解決方案命名為 "WordCounter"。Name the project "TextUtils" (a short name for "Text Utilities") and the solution "WordCounter". 保持選取 [在解決方案目錄中建立專案目錄] 。Leave Create a project directory within the solution directory checked. 選取 [建立] 。Select Create.

    Visual Studio for Mac [新增專案] 對話方塊選項

  3. 在 [解決方案] 提要欄位中,展開 TextUtils 節點以顯示範本所提供的類別檔案 Class1.csIn the Solution sidebar, expand the TextUtils node to reveal the class file provided by the template, Class1.cs. 以滑鼠右鍵按一下該檔案,從操作功能表選取 [重新命名] ,並將檔案重新命名為 WordCount.csRight-click the file, select Rename from the context menu, and rename the file to WordCount.cs. 開啟檔案,並以下列程式碼取代內容:Open the file and replace the contents with the following code:

    using System;
    using System.Linq;
    
    namespace TextUtils
    {
        public static class WordCount
        {
            public static int GetWordCount(string searchWord, string inputString)
            {
                // Null check these variables and determine if they have values.
                if (string.IsNullOrEmpty(searchWord) || string.IsNullOrEmpty(inputString))
                {
                    return 0;
                }
    
                // Convert the string into an array of words.
                var source = inputString.Split(new char[] { '.', '?', '!', ' ', ';', ':', ',' },
                                               StringSplitOptions.RemoveEmptyEntries);
    
                // Create the query. Use ToLowerInvariant to match uppercase/lowercase strings.   
                var matchQuery = from word in source
                                 where word.ToLowerInvariant() == searchWord.ToLowerInvariant()
                                 select word;
    
                // Count the matches, which executes the query. Return the result.
                return matchQuery.Count();
            }
        }
    }
    
  4. 使用下列三種方法之一來儲存檔案:使用鍵盤快速鍵 +s、從功能表選取 [檔案] > [儲存] ,或以滑鼠右鍵按一下檔案的索引標籤,並從操作功能表選取 [儲存] 。Save the file by using any of three different methods: use the keyboard shortcut +s, select File > Save from the menu, or right-click on the file's tab and select Save from the contextual menu. 下圖顯示 IDE 視窗︰The following image shows the IDE window:

    Visual Studio for Mac IDE 視窗,其中包含程式庫檔案和方法

  5. 選取 IDE 視窗下邊界中的 [錯誤] ,以開啟 [錯誤] 面板。Select Errors in the margin at the bottom of the IDE window to open the Errors panel. 選取 [建置輸出] 按鈕。Select the Build Output button.

    Visual Studio Mac IDE 的下邊界,顯示 [錯誤] 按鈕

  6. 從功能表選取 [建置] > [全部建置] 。Select Build > Build All from the menu.

    解決方案隨即建置。The solution builds. 建置輸出面板會顯示建置成功。The build output panel shows that the build is successful.

    [錯誤] 面板的 Visual Studio Mac [建置輸出] 窗格,其中包含「建置成功」訊息

建立測試專案Creating a test project

單元測試能在開發與發佈期間提供自動化的軟體測試。Unit tests provide automated software testing during your development and publishing. 您在本教學課程中使用的測試架構是 xUnit (版本 2.2.0 或更新版本),這會在下列步驟中 xUnit 測試專案加入解決方案時自動安裝:The testing framework that you use in this tutorial is xUnit (version 2.2.0 or later), which is installed automatically when the xUnit test project is added to the solution in the following steps:

  1. 在 [解決方案] 提要欄位中,以滑鼠右鍵按一下 WordCounter 解決方案,並選取 [新增] > [新增專案] 。In the Solution sidebar, right-click the WordCounter solution and select Add > Add New Project.

  2. 在 [新增專案] 對話方塊中,從 [.NET Core] 節點選取 [測試] 。In the New Project dialog, select Tests from the .NET Core node. 選取 [xUnit 測試專案] ,接著選取 [下一步] 。Select the xUnit Test Project followed by Next.

    建立 xUnit 測試專案的 Visual Studio Mac [新增專案] 對話方塊

  3. 將新專案命名為 "TestLibrary",並選取 [建立] 。Name the new project "TestLibrary" and select Create.

    提供專案名稱的 Visual Studio Mac [新增專案] 對話方塊

  4. 為了讓測試程式庫能搭配 WordCount 類別使用,請將參考加入 TextUtils 專案。In order for the test library to work with the WordCount class, add a reference to the TextUtils project. 在 [解決方案] 提要欄位中,以滑鼠右鍵按一下 [TestLibrary] 底下的 [相依性] 。In the Solution sidebar, right-click Dependencies under TestLibrary. 從操作功能表選取 [編輯參考] 。Select Edit References from the context menu.

  5. 在 [編輯參考] 對話方塊中,選取 [專案] 索引標籤上的 [TextUtils] 專案。選取 [確定] 。In the Edit References dialog, select the TextUtils project on the Projects tab. Select OK.

    Visual Studio Mac [編輯參考] 對話方塊

  6. 在 [TestLibrary] 專案中,將 UnitTest1.cs 檔案重新命名為 TextUtilsTests.csIn the TestLibrary project, rename the UnitTest1.cs file to TextUtilsTests.cs.

  7. 開啟檔案,並以下列內容取代程式碼:Open the file and replace the code with the following:

    using Xunit;
    using TextUtils;
    using System.Diagnostics;
    
    namespace TestLibrary
    {
        public class TextUtils_GetWordCountShould
        {
            [Fact]
            public void IgnoreCasing()
            {
                var wordCount = WordCount.GetWordCount("Jack", "Jack jack");
    
                Assert.NotEqual(2, wordCount);
            }
        }
    }
    

    下圖顯示具有單元測試程式碼的 IDE。The following image shows the IDE with the unit test code in place. 請留意 Assert.NotEqual 陳述式。Pay attention to the Assert.NotEqual statement.

    IDE 主視窗中的 Visual Studio for Mac 初始單元測試

    請務必讓新的測試失敗一次,以確認其測試邏輯正確。It's important to make a new test fail once to confirm its testing logic is correct. 該方法會傳入 "Jack" (大寫) 這個名字,以及具有 "Jack" 和 "jack" (大寫與小寫) 的字串。The method passes in the name "Jack" (uppercase) and a string with "Jack" and "jack" (uppercase and lowercase). 如果 GetWordCount 方法能正常運作,它會針對搜尋文字傳回兩個實例計數。If the GetWordCount method is working properly, it returns a count of two instances of the search word. 為了刻意讓此測試失敗,您會先實作測試,以判斷提示 GetWordCount 方法沒有傳回搜尋文字 "Jack" 的兩個實例。In order to fail this test on purpose, you first implement the test asserting that two instances of the search word "Jack" aren't returned by the GetWordCount method. 繼續進行下一個步驟以刻意讓測試失敗。Continue to the next step to fail the test on purpose.

  8. 開啟螢幕右側的 [單元測試] 面板。Open the Unit Tests panel on the right side of the screen.

    Visual Studio for Mac [單元測試] 面板

  9. 按一下固定圖示維持面板開啟。Click the Dock icon to keep the panel open.

    Visual Studio for Mac [單元測試] 面板固定圖示

  10. 按一下 [全部執行] 按鈕。Click the Run All button.

    測試會失敗,這是正確的結果。The test fails, which is the correct result. 測試方法會判斷提示 inputString 的兩個實例 ("Jack") 沒有從提供給 GetWordCount 方法的字串 "Jack jack" 傳回。The test method asserts that two instances of the inputString, "Jack," aren't returned from the string "Jack jack" provided to the GetWordCount method. 由於文字大小寫的因素已經在 GetWordCount 方法中排除,因此會傳回兩個實例。Since word casing was factored out in the GetWordCount method, two instances are returned. 2「不等於」 2 的判斷提示將會失敗。The assertion that 2 is not equal to 2 fails. 這是正確的結果,並證明測試的邏輯是良好的。This is the correct outcome, and the logic of our test is good.

    Visual Studio for Mac 測試失敗顯示畫面

  11. Assert.NotEqual 變更為 Assert.Equal 來修改 IgnoreCasing 測試方法。Modify the IgnoreCasing test method by changing Assert.NotEqual to Assert.Equal. 使用鍵盤快速鍵 +s、功能表的 [檔案] > [儲存] ,或是以滑鼠右鍵按一下檔案的索引標籤,並從操作功能表選取 [儲存] 來儲存檔案。Save the file by using the keyboard shortcut +s, File > Save from the menu, or right-clicking on the file's tab and selecting Save from the context menu.

    藉由將 inputString "Jack jack" 傳入 GetWordCount,您預期 searchWord "Jack" 會傳回兩個實例。You expect that the searchWord "Jack" returns two instances with inputString "Jack jack" passed into GetWordCount. 按一下螢幕底部 [單元測試] 面板中的 [執行測試] 按鈕或 [測試結果] 面板中的 [重新執行測試] 按鈕來重新執行測試。Run the test again by clicking the Run Tests button in the Unit Tests panel or the Rerun Tests button in the Test Results panel at the bottom of the screen. 測試就會成功。The test passes. 字串 "Jack jack" 中有兩個 "Jack" 實例 (忽略大小寫),且測試判斷提示為 trueThere are two instances of "Jack" in the string "Jack jack" (ignoring casing), and the test assertion is true.

    Visual Studio for Mac 測試成功顯示畫面

  12. 使用 Fact 測試個別的傳回值,只是單元測試的初步用途。Testing individual return values with a Fact is only the beginning of what you can do with unit testing. 另一個強大的技術,是使用 Theory 一次測試數個值。Another powerful technique allows you to test several values at once using a Theory. 將下列方法加入至 TextUtils_GetWordCountShould 類別。Add the following method to your TextUtils_GetWordCountShould class. 在您加入此方法後,您在類別中會有兩個方法:You have two methods in the class after you add this method:

    [Theory]
    [InlineData(0, "Ting", "Does not appear in the string.")]
    [InlineData(1, "Ting", "Ting appears once.")]
    [InlineData(2, "Ting", "Ting appears twice with Ting.")]
    public void CountInstancesCorrectly(int count,
                                        string searchWord,
                                        string inputString)
    {
        Assert.NotEqual(count, WordCount.GetWordCount(searchWord,
                                                   inputString));
    }
    

    CountInstancesCorrectly 會檢查 GetWordCount 方法是否能正確計數。The CountInstancesCorrectly checks that the GetWordCount method counts correctly. InlineData 提供要檢查的計數、搜尋文字,以及輸入字串。The InlineData provides a count, a search word, and an input string to check. 測試方法會針對每一行資料各執行一次。The test method runs once for each line of data. 請注意,即使您知道資料中的計數是正確的,且值符合 GetWordCount 方法所傳回的計數,仍然要再次先使用 Assert.NotEqual 來判斷提示出錯誤。Note once again that you're asserting a failure first by using Assert.NotEqual, even when you know that the counts in the data are correct and that the values match the counts returned by the GetWordCount method. 執行刻意讓測試失敗的步驟,起初看起來似乎有點浪費時間,但是先透過讓測試失敗以檢查測試的邏輯,是一項對測試邏輯很重要的檢查。Performing the step of failing the test on purpose might seem like a waste of time at first, but checking the logic of the test by failing it first is an important check on the logic of your tests. 當您遇到預期會失敗卻成功的測試方法時,代表測試邏輯中有錯誤。When you come across a test method that passes when you expect it to fail, you've found a bug in the logic of the test. 每次當您建立測試方法時,都值得採取此步驟。It's worth the effort to take this step every time you create a test method.

  13. 儲存檔案,然後再次執行測試。Save the file and run the tests again. 大小寫的測試會通過,但是三個計數測試會失敗。The casing test passes but the three count tests fail. 這正是您預期會發生的情況。This is exactly what you expect to happen.

    Visual Studio for Mac 預期的測試失敗

  14. Assert.NotEqual 變更為 Assert.Equal 來修改 CountInstancesCorrectly 測試方法。Modify the CountInstancesCorrectly test method by changing Assert.NotEqual to Assert.Equal. 儲存檔案。Save the file. 再次執行測試。Run the tests again. 所有測試皆通過。All tests pass.

    Visual Studio for Mac 預期的測試成功

新增主控台應用程式Adding a console app

  1. 在 [解決方案] 提要欄位中,以滑鼠右鍵按一下 WordCounter 解決方案。In the Solution sidebar, right-click the WordCounter solution. 從 [.NET Core] > [應用程式] 範本中選取範本,來新增 [主控台應用程式] 專案。Add a new Console Application project by selecting the template from the .NET Core > App templates. 選取 [下一步] 。Select Next. 將專案命名為 WordCounterAppName the project WordCounterApp. 選取 [建立] 以在解決方案中建立專案。Select Create to create the project in the solution.

  2. 在 [解決方案] 提要欄位中,以滑鼠右鍵按一下新的 [WordCounterApp] 專案的 [相依性] 節點。In the Solutions sidebar, right-click the Dependencies node of the new WordCounterApp project. 在 [編輯參考] 對話方塊中,選取 [TextUtils] 並選取 [確定] 。In the Edit References dialog, check TextUtils and select OK.

  3. 開啟 Program.cs 檔案。Open the Program.cs file. 使用下列內容取代程式碼:Replace the code with the following:

    using System;
    using TextUtils;
    
    namespace WordCounterApp
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("Enter a search word:");
                var searchWord = Console.ReadLine();
                Console.WriteLine("Provide a string to search:");
                var inputString = Console.ReadLine();
    
                var wordCount = WordCount.GetWordCount(searchWord, inputString);
    
                var pluralChar = "s";
                if (wordCount == 1)
                {
                    pluralChar = string.Empty;
                }
    
                Console.WriteLine($"The search word {searchWord} appears " +
                                  $"{wordCount} time{pluralChar}.");
            }
        }
    }
    
  4. 若要在主控台視窗而非 IDE 中執行應用程式,請以滑鼠右鍵按一下 WordCounterApp 專案,選取 [選項] ,並開啟 [組態] 底下的 [預設] 節點。To run the app in a console window instead of the IDE, right-click the WordCounterApp project, select Options, and open the Default node under Configurations. 選取 [在外部主控台上執行] 方塊。Check the box for Run on external console. 保持選取 [暫停主控台輸出] 選項。Leave the Pause console output option checked. 此設定會造成應用程式在主控台視窗中繁衍,讓您可以輸入 Console.ReadLine 陳述式的輸入。This setting causes the app to spawn in a console window so that you can type input for the Console.ReadLine statements. 如果您讓應用程式在 IDE 中執行,便只能看見 Console.WriteLine 陳述式的輸出。If you leave the app to run in the IDE, you can only see the output of Console.WriteLine statements. Console.ReadLine 陳述式不能在 IDE 的 [應用程式輸出] 面板中運作。Console.ReadLine statements do not work in the IDE's Application Output panel.

    Visual Studio for Mac [專案選項] 視窗

  5. 由於目前版本的 Visual Studio for Mac 無法在解決方案執行時執行測試,您必須直接執行主控台應用程式。Because the current version of Visual Studio for Mac cannot run the tests when the solution is run, you run the console app directly. 以滑鼠右鍵按一下 WordCounterApp 專案,並從操作功能表中選取 [執行項目] 。Right-click on the WordCounterApp project and select Run item from the context menu. 如果您嘗試使用 [播放] 按鈕執行應用程式,測試執行器和應用程式會無法執行。If you attempt to run the app with the Play button, the test runner and app fail to run. 如需此問題工作狀態的詳細資訊,請參閱 xunit/xamarinstudio.xunit (#60) (英文)For more information on the status of the work on this issue, see xunit/xamarinstudio.xunit (#60). 當您執行應用程式時,請根據主控台視窗中的提示,提供搜尋文字和輸入字串的值。When you run the app, provide values for the search word and input string at the prompts in the console window. 應用程式會指出搜尋文字在字串中出現的次數。The app indicates the number of times the search word appears in the string.

    Visual Studio for Mac 主控台視窗,顯示您的應用程式正在執行

  6. 最後一個要探索的功能,是使用 Visual Studio for Mac 進行偵錯。The last feature to explore is debugging with Visual Studio for Mac. Console.WriteLine 陳述式上設定中斷點:選取行 23 的左邊界,您會在程式碼行旁邊看見一個紅色圓圈。Set a breakpoint on the Console.WriteLine statement: Select in the left margin of line 23, and you see a red circle appear next to the line of code. 或者,選取程式碼行上的任何位置,並從功能表選取 [執行] > [切換中斷點] 。Alternatively, select anywhere on the line of code and select Run > Toggle Breakpoint from the menu.

    Visual Studio for Mac 中斷點設定

  7. 以滑鼠右鍵按一下 WordCounterApp 專案。Right-click the WordCounterApp project. 從操作功能表選取 [開始偵錯項目] 。Select Start Debugging item from the context menu. 當應用程式執行時,輸入搜尋的文字 "cat",以及When the app runs, enter the search word "cat" and "The dog chased the cat, but the cat escaped." 要搜尋的字串 "The dog chased the cat, but the cat escaped"。for the string to search. 當到達 Console.WriteLine 陳述式時,程式執行會在執行該陳述式之前中止。When the Console.WriteLine statement is reached, program execution halts before the statement is executed. 在 [區域變數] 索引標籤中,您可以看到 searchWordinputStringwordCountpluralChar 值。In the Locals tab, you can see the searchWord, inputString, wordCount, and pluralChar values.

    Visual Studio for Mac 偵錯工具程式執行已停止

  8. 在 [即時運算] 窗格中,輸入 "wordCount = 999",並按 Enter。In the Immediate pane, type "wordCount = 999;" and press Enter. 這會將無意義值 999 指派給 wordCount 變數,顯示您可以在進行偵錯時取代變數值。This assigns a nonsense value of 999 to the wordCount variable showing that you can replace variable values while debugging.

    Visual Studio for Mac 變更 [即時運算] 視窗中的值

  9. 在工具列中,按一下 [繼續] 箭號。In the toolbar, click the continue arrow. 查看主控台視窗中的輸出。Look at the output in the console window. 它會報告您在對應用程式進行偵錯時所設定的不正確值,999。It reports the incorrect value of 999 that you set when you were debugging the app.

    Visual Studio for Mac 工具列中的 [繼續] 按鈕

    Visual Studio for Mac 主控台視窗輸出

另請參閱See also