繁体   English   中英

错误单元测试webapi控制器

[英]Error unit testing webapi controller

我正在使用AspNet Web Api Client 5.0,我正在尝试对web api控制器进行单元测试。

var encservice = new EncryptionService();
var acctservice = FakeServices.GetAccountService();
var controller = new AccountController(acctservice, encservice);
controller.Request = new HttpRequestMessage();

当代码

controller.Request.SetConfiguration(new HttpConfiguration());

被执行我遇到了异常

消息 :无法加载文件或程序集“Newtonsoft.Json,Version = 4.5.0.0,Culture = neutral,PublicKeyToken = 30ad4fe6b2a6aeed”或其中一个依赖项。 定位的程序集的清单定义与程序集引用不匹配。 (HRESULT异常:0x80131040)

资料来源: System.Net.Http.Formatting

Stacktrace :位于System.Net的System.Net.Http.Forttting.Medic中的System.Net.Http.Forttting.Medie中的System.Net.Http.Formatting.MediaTypeFormatterCollection.CreateDefaultFormatters()处的System.Net.Http.Formatting.JsonMediaTypeFormatter..ctor() .HttpConfiguration.DefaultFormatters()位于System.Web.Http.HttpConfiguration..ctor(HttpRouteCollection路由)的System.Web.Http.HttpConfiguration..ctor()位于EMR.Test.Controller.AccountControllerTest.Should_Get()的c中:\\ PremiumProjectsCollection \\ emr \\ src \\ EMRAzure \\ EMRAzure \\ EMR.Test \\ Controller \\ AccountControllerTest.cs:第34行

我使用的newsoft.json的版本是6.0

我的配置文件中也有一个程序集重定向

 <dependentAssembly>
    <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
  </dependentAssembly>

我使用的测试运行器是MStest,VS2012

您需要添加程序集重定向

<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json"
                          publicKeyToken="30ad4fe6b2a6aeed"
                          culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

(假设Newtonsoft.Json的程序集版本正好是6.0.0.0 。)

(注意以下注释是指具有此问题的Web Api客户端项目)

我对Newtonsoft.Json的版本有同样的问题,所以我删除了旧版本的引用,并使用Package Manager Console在我的Web Api Client Library和Test Project上安装了最新版本的Newtonsoft.Json。

安装包Newtonsoft.Json -Version 6.0.8(注意你可能需要找出哪个是最新版本)

问题仍然存在,所以我意识到System.Net.Http.Formatting和我最新版本的Json之间出现了崩溃。 要解决此问题,请删除System.Net.Http和System.Net.Http.Formatting引用,并通过Nuget安装WebApi客户端库,如下所示:

安装包Microsoft.AspNet.WebApi.Client

这解决了我。

我自己没试过,但是2012年的mstest似乎有一个错误。 你必须使用.testsettings文件来获取app.config。

请参阅以下链接: http//social.msdn.microsoft.com/Forums/vstudio/en-US/234926d1-42c0-4ebb-af39-1626e72f6c39/why-does-assemblybinding-work-only-if-testsettings-file -is-二手vs2012rc?论坛= vsunittest

我几天前遇到了同样的问题,我花了几个小时才找到这个问题的解决方案。

我正在测试一个安装了最新版NewtonSoft的单元,而我的测试项目有一个旧版本。

我通过右键单击解决方案资源管理器中的解决方案,通过“管理Nuget软件包解决方案”选项,在我的解决方案中整合了此库的版本。

这将更新当前解决方案下项目中存在的所有NewtonSoft库,并从VisualStudio在解决方案目录中名为packages的文件夹中创建的包控件中删除所有旧版本。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM