1

我使用一个SupplierController类及其SupplierControllerTest类来验证我的期望。

如果我的SupplierController类继承自 System.Web.Mvc.Controller 则测试运行正常。如果我的SupplierController类继承自然ServiceStack.Mvc.ServiceStackController后测试抛出异常。我正在使用Moq来测试它。

这是两个类:

测试班

  [TestFixture]
  public class SupplierControllerTests
  {
     [Test]
     public void Should_call_create_view_on_view_action()
     {
        var nafCodeServiceMock = new Mock<INafCodeService>();
        var countryServiceMock = new Mock<ICountryService>();
        var controller = new SupplierController();
        controller.NafCodeService = nafCodeServiceMock.Object;
        controller.CountryService = countryServiceMock.Object;

        nafCodeServiceMock.Setup(p => p.GetAll()).Returns(new List<NafCode> { new NafCode { Code = "8853Z", Description = "naf code test" } });
        countryServiceMock.Setup(p => p.GetAll()).Returns(new List<Country> { new Country { Name="France"  } });

        var result = controller.Create() as ViewResult;
        Assert.That(result, Is.Not.Null);
    }
 }

控制器类

  public class SupplierController : ServiceStackController
  {
     public ISupplierService SupplierService { get; set; }
     public IManagerService ManagerService { get; set; }
     public INafCodeService NafCodeService { get; set; }
     public ICountryService CountryService { get; set; }

     public ActionResult Create()
     {
       var model = new SupplierModel();
       model.Country = "France";
       return View(model);
     }
   }

供应商模型类

  public class SupplierModel
  {
     public string Country { get; set; }
  }

抛出的错误是:

测试 'SupplierControllerTests.Should_call_create_view_on_view_action' 失败:System.MethodAccessException : Échec de la tentative d'accès de la 方法 'SupplierController.Create()' à la 方法 'System.Web.Mvc.Controller.View(System.Object)'。Controllers\SupplierController.cs(51,0): à SupplierController.Create() Controllers\SupplierControllerTests.cs(33,0): à SupplierControllerTests.Should_call_create_view_on_view_action()

翻译这意味着:

访问方法“SupplierController.Create()”失败。

4

1 回答 1

1

I'll take a crack at it. I don't know what version of MVC you're using but my guess is that ServiceStack is compiled against an older version. You will need binding redirect. Now usually, the binding redirect is added as part of the MVC project templates but in your unit test project, you'll have to do manually (this explains why you only experience this error in your unit test).

In your unit test project app.config (this example is to redirect from MVC2 to MVC3. Adapt it to your case):

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>
于 2013-09-26T21:20:52.450 回答