xunit 测试网络 api 2 控制器:抛出 Xunit.Sdk.IsTypeException

xunit testing web api 2 controller : throws Xunit.Sdk.IsTypeException

我不想在 Web api 控制器上测试插入方法。方法 returns 一个 CreatedNegotiatedContentResult。一切顺利,直到 Assert...

Assert.IsType(typeof(CreatedNegotiatedContentResult<Justif>), result);

繁荣...

Xunit.Sdk.IsTypeException was unhandled by user code
  Actual=System.Web.Http.Results.CreatedNegotiatedContentResult`1[[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
  ActualTitle=Actual
  Expected=System.Web.Http.Results.CreatedNegotiatedContentResult`1[[HubHacienda.Justif, HubHacienda, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]
  ExpectedTitle=Expected
  HResult=-2146233088
  Message=Assert.IsType() Failure
Expected: System.Web.Http.Results.CreatedNegotiatedContentResult`1[[HubHacienda.Justif, HubHacienda, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]
Actual:   System.Web.Http.Results.CreatedNegotiatedContentResult`1[[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
  Source=xunit.assert
  UserMessage=Assert.IsType() Failure
  StackTrace:
       at Xunit.Assert.IsType(Type expectedType, Object object) in C:\BuildAgent\work\cb37e9acf085d108\src\xunit.assert\Asserts\TypeAsserts.cs:line 99
       at HubHacienda.Tests.JustifsControllerTest.Post_WhenModelValid_ShouldReturnSuccess() in C:\NotilusTNE\Sources\Hub\Hub Hacienda\Dev\HubHacienda\HubHacienda.Tests\JustifsControllerTests.cs:line 52
  InnerException: 

这是我的测试框架炸了?这不可能吧?

好的,这似乎是一个 xunit 错误。问题是我正在比较 SystemType 形式的泛型类型。 xunit 项目中的 typeof() 运算符 returns 表示我的 dll 的强名称,而 result.GetType() returns 系统 dll 的强名称。

解决方法是只比较 Type.Name...

System.Type expectation = typeof(System.Web.Http.Results.CreatedNegotiatedContentResult<Justif>);
System.Type tristeRealite = result.GetType();
Assert.Equal(expectation.Name, tristeRealite.Name);