你如何单元测试的ASP.NET核心控制器或模型对象? [英] How do you unit test an ASP.NET Core controller or model object?

查看:171
本文介绍了你如何单元测试的ASP.NET核心控制器或模型对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在preVIEW过程中得到一些控制器,型号和存储库(数据访问)下的单元测试的C#类,在Visual Studio 2015年,与ASP.NET MVC核心(ASP.NET 5,现在叫ASP.Net核心)的应用程序。

I am trying to get some controller, model, and repository (data access) C# classes under unit test, in Visual Studio 2015, with ASP.NET Core MVC (ASP.NET 5 during the preview, now called ASP.Net Core) apps.

我有以下结构:

   Solution
       |
      src
       | 
       |-- ITConsole       <- main app (ASP.NET MVC, DNX 4.5.1)
       | 
       `-- ITConsoleTests  <- What kind of project should this be?

该MainApp是使用DNX 4.5.1,但似乎如果我创建一个标准的NUnit的单元测试的应用程序,它只是作为一个经典的.NET Framework类库,打靶的.NET Framework 4.5.2,而不是作为一个Web类库,可以与我的主要应用程序的工作。

The MainApp is using DNX 4.5.1, but it seems that if I create a standard nUnit Unit test app, it's only available as a classic .NET Framework class library, targetting .NET Framework 4.5.2, not as a Web Class Library that can work with my main app.

所以,以防万一它可能工作作为一个典型的.NET框架微软单元测试框架项目(.NET程序集),我试图手动查找并添加引用(通过添加引用,浏览)来获取.NET依赖解决。我知道,.NET程序集引用是可悲的非传递。所以,如果UnitTest.dll有MainApp.dll参考,并MainApp.dll依赖于ASP.NET MVC,和其他一切所依赖的,我必须这样做我自己。这就是我想要做的。我加入一个参考 C:\\ dev的\\演示\\ ITConsole \\工件\\ BIN \\ ITConsole \\调试\\ dnx451 \\ ITConsole.dll 进入我的单元测试项目,所以我可以开始拿到code编译。该单元测试类编译,但他们不跑,可能是因为试图添加到ASP.NET参考的一塌糊涂。

So, just in case it might work as a classic .NET framework Microsoft Unit Test framework project (.net assembly), I tried to manually find and add references (by add reference, and browse) to get the .NET dependencies to resolve. I am aware that .NET assembly references are sadly non-transitive. So if UnitTest.dll has a reference to MainApp.dll, and MainApp.dll depends on ASP.NET MVC, and everything else that it depends on, I have to do that myself. That is what I'm trying to do. I added a reference to C:\dev\Demo\ITConsole\artifacts\bin\ITConsole\Debug\dnx451\ITConsole.dll into my unit test project so I could begin to get the code to compile. The unit test classes compile but they don't run, probably because of the mess of trying to add a reference to ASP.NET.

现在,即使我已经加入到Common.Logging.Core和Common.Logging,参考当我点击运行所有的测试资源管理器,我得到这个错误:

Right now, even though I have added a reference to Common.Logging.Core, and Common.Logging, when I click "Run All" on the Test explorer I get this error:

Test Name:  TestStudyLogReadDocument
Test FullName:  ITConsoleTests.ITConsoleTestStudyLog.TestStudyLogReadDocument
Test Source:    C:\dev\Demo\ITConsole\ITConsoleTests\ITConsoleTestStudyLog.cs : line 52
Test Outcome:   Failed
Test Duration:  0:00:00.0712058

Result StackTrace:  
at Couchbase.Configuration.Client.ClientConfiguration..ctor()
   at ITConsole.Repository.StudyLogRepository..ctor() in C:\dev\Demo\ITConsole\src\ITConsole\Repository\StudyLogRepository.cs:line 39
   at ITConsoleTests.ITConsoleTestStudyLog.SetupDb() in C:\dev\Demo\ITConsole\ITConsoleTests\ITConsoleTestStudyLog.cs:line 30
   at ITConsoleTests.ITConsoleTestStudyLog.TestStudyLogReadDocument() in C:\dev\Demo\ITConsole\ITConsoleTests\ITConsoleTestStudyLog.cs:line 53
Result Message: 
Test method ITConsoleTests.ITConsoleTestStudyLog.TestStudyLogReadDocument threw exception: 
System.IO.FileLoadException: Could not load file or assembly 'Common.Logging.Core, Version=3.1.0.0, Culture=neutral, PublicKeyToken=af08829b84f0328e' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

(在这个问题被问的时候......)的asp.net mvc的5 preVIEW无模板可以为您生成单元测试。你能连单元测试一个全新的ASP.NET核心应用?见下面的截图,例如你上手单元测试正常的方式是如何不提供VS 2015年使用MSTEST。

(At the time this question was asked...) None of the asp.net 5 mvc preview templates can generate unit tests for you. Can you even unit test a shiny new ASP.NET Core application? See screenshot below, for example of how the normal way you get started unit testing is not available in VS 2015 using MSTEST.

为您服务没有单元测试

推荐答案

更​​新:的xUnit仍然是一个伟大的想法,但这个答案现在已经过时了,因为你可以此外,如果你想使用ASP.NET核心使用MSTEST。 (2016年6月1日)

UPDATE: XUnit is still a great idea, but this answer is outdated now because you can also use MSTEST if you want with ASP.NET core. (June 1, 2016)

最近玩过的xUnit说明LINK:优秀的指令可能会更加频繁更新比这个答案在维基的xUnit被发现。

MOST RECENT XUNIT INSTRUCTIONS LINK: Excellent instructions that may be updated more often than this answer are found at the xUnit wiki.

IDE解决方法:手动查找并删除%TEMP%\\ VisualStudioTestExplorerExtensions时,Visual Studio中去笨,不会检测,并显示您的测试

IDE WORKAROUND: manually find and delete %TEMP%\VisualStudioTestExplorerExtensions when Visual Studio goes stupid and won't "detect" and show you your tests.

截至2016年5月,随着最近RC2所取代ASP.NET 1.0的核心RC1,它仍然没有出现可能使用与ASP.NET核心(原ASP.NET 5)微软的标准单元测试框架,以及出现的xUnit成为RC1和RC2一个不错的选择。

As of May 2016, with ASP.NET Core 1.0 RC1 recently superceded by RC2, it still does not appear possible to use the standard Microsoft Unit Test framework with ASP.NET Core (Formerly ASP.NET 5), and XUnit appears to be a good choice for RC1 and RC2.

您可以得到XUnit.net单元测试与ASP.NET核心1.0.0-RC1工作,使用官方的说明]的 2在具有特定的的xUnit GitHub的项目入门的情况。

You can get XUnit.net unit testing to work with ASP.NET Core 1.0.0-RC1, using the official instructions]2 at the XUnit github project which has a specific ".net core getting started" case.

您还可以安装的xUnit新项目模板,提供定期完整的.NET和.NET核心模板化的单元测试项目。单击工具,然后扩展和更新型的xUnit,并找到的xUnit测试项目模板安装模板。不要安装的xUnit测试运行器,你不需要它。

You can also install the XUnit New Project Template that provides a templated unit test project for regular full .net and .net core. Click Tools and then Extensions and Updates type in XUnit, and find xUnit Test Project TEMPLATE and install the TEMPLATE. DO NOT INSTALL ANY xUNIT TEST RUNNER, YOU DO NOT NEED IT.

我创建了一个工作示例,并上传到到位桶:

I have created a working sample and uploaded it to bitbucket:

https://bitbucket.org/wpostma/aspnet5mvc6xunitdemo

如果你没有做善变,你可以从到位桶下载一个ZIP。

If you don't have mercurial, you can download a zip from bitbucket.

该演示包括一个测试通过,一个测试失败。

The demo includes one test that passes, and one test that fails.

快速摘​​要:


  1. 您的Visual Studio 2015年,包括UPDATE2和1.0.0 preVIEW工具(如最新的五月2016年)。

  1. You have Visual Studio 2015 including Update2 and the "1.0.0 preview" tools (latest as of May 2016).

创建Web类库不是一个单元测试项目。

Create a Web Class Library NOT a Unit Test Project.

添加的xUnit引用它,并修复project.json(下面的例子)。

Add XUnit references to it, and fix your project.json (example below).

编写类(下面的例子)。

Write your class (example below).

里面的IDE,或外部的IDE,键入测试资源管理器运行测试在 DNX。测试并检查输出(下面的例子)。

Run tests with Test Explorer inside ide, or outside ide, type in dnx . tests and examine output (example below).

project.json为1.0.0-RC2参照演示组件和的xUnit:

project.json for 1.0.0-rc2 with reference to a demo assembly and xunit:

 {
  "version": "1.0.0-*",

  "testRunner": "xunit",

  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.0-rc2-3002702",
      "type": "platform"
    },

    "dotnet-test-xunit": "1.0.0-rc2-*",

    "xunit": "2.1.0",


    "YetAnotherWebbyDemo": "1.0.0-*"
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dotnet5.6",
        "dnxcore50",
        "portable-net45+win8"
      ]
    }
  }
}

单元测试类(whatever.cs):

Unit test class (whatever.cs):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using Xunit;

using YetAnotherWebbyDemo.Models;

namespace YetAnotherWebbyDemoTests
{
    // This project can output the Class library as a NuGet Package.
    // To enable this option, right-click on the project and select the Properties menu item. In the Build tab select "Produce outputs on build".
    public class TestBasics
    {
        [Fact]
        public void TestAdd()
        {

            TestableModelClass TestMe = new TestableModelClass();


            Assert.True(TestMe.Add(3, 2) == 5, "Basic Math Failure");

            Assert.True(TestMe.Add(-3, -2) == -5, "Basic Math Failure");
        }

    }
}

这是命令行中RC1当我们用DNX输出示例:

Example output from commandline in RC1 when we used dnx:

C:\dev\Demo\YetAnotherWebbyDemo\src\YetAnotherWebbyDemoTests>dnx . test

xUnit.net DNX Runner (32-bit DNX 4.5.1)
  Discovering: YetAnotherWebbyDemoTests
  Discovered:  YetAnotherWebbyDemoTests
  Starting:    YetAnotherWebbyDemoTests
    YetAnotherWebbyDemoTests.TestBasics.TestAdd [FAIL]
      Basic Math Failure
      Expected: True
      Actual:   False
      Stack Trace:
        YetAnotherWebbyDemoTestBasics.cs(25,0): at YetAnotherWebbyDemoTests.Test
Basics.TestAdd()
  Finished:    YetAnotherWebbyDemoTests
=== TEST EXECUTION SUMMARY ===
   YetAnotherWebbyDemoTests  Total: 1, Errors: 0, Failed: 1, Skipped: 0, Time: 0.263s

例输出RC2,我们正在使用 DOTNET

D:\dev\aspnet5mvc6xunitdemo\src\YetAnotherWebbyDemoTests>dotnet test
Project YetAnotherWebbyDemo (.NETCoreApp,Version=v1.0) was previously compiled. Skipping compilation.
Project YetAnotherWebbyDemoTests (.NETCoreApp,Version=v1.0) was previously compiled. Skipping compilation.
xUnit.net .NET CLI test runner (64-bit win10-x64)
  Discovering: YetAnotherWebbyDemoTests
  Discovered:  YetAnotherWebbyDemoTests
  Starting:    YetAnotherWebbyDemoTests
    YetAnotherWebbyDemoTests.TestBasics.TestAdd [FAIL]
      Basic Math Failure
      Expected: True
      Actual:   False
      Stack Trace:
        D:\dev\aspnet5mvc6xunitdemo\src\YetAnotherWebbyDemoTests\YetAnotherWebbyDemoTestBasics.cs(26,0): at YetAnotherWebbyDemoTests.TestBasics.TestAdd()
  Finished:    YetAnotherWebbyDemoTests
=== TEST EXECUTION SUMMARY ===
   YetAnotherWebbyDemoTests  Total: 1, Errors: 0, Failed: 1, Skipped: 0, Time: 0.205s
SUMMARY: Total: 1 targets, Passed: 0, Failed: 1.

这篇关于你如何单元测试的ASP.NET核心控制器或模型对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆