MyTested.AspNetCore.Mvc icon indicating copy to clipboard operation
MyTested.AspNetCore.Mvc copied to clipboard

Call a method in derived class instead of the parent class

Open amunim opened this issue 3 years ago • 0 comments

Describe your issue I have a CMS system which by default every controller gets static content. Some sites need more additional data hence it derives from the BaseApiController and overrides the default behavior so as to include relevant data. The way it works is that using ControllerContext.ActionDescriptor.ControllerName, we can get the name of the page controller we are at, this works when when the class overrides the default method. But in method where it is not overridden, rather inherited. The value is not up to date only in tests.

Expected behavior ControllerContext.ActionDescriptor.ControllerName to have derived controller name.

Now, the code

[ApiController]
[Route("[controller]")]
public class BaseApiController : ControllerBase
{
    public virtual async Task<ActionResult<MainLayout>> Index([FromBody]Session session = null)
    {
        return HandleResult(await GetContent<MainLayout>(IDMembership: session?.IDMembership));
    }
}

public class AboutUsController: BaseApiController //not working in tests, but works in browser
{

}

public class ReviewsController: BaseApiController //works in tests, and in the browser
{
   [HttpGet()]
   public override async Task<ActionResult<MainLayout>> Index([FromBody]Session session = null)
   {
       return new ReviewsDTO; //some DTO derived from MainLayout
   }
}
Tests
[Collection("Test")]
public class StaticPages
{
    [Fact]
    public void About() //but will work for Reviews
    {
        MyController<AboutUsController>
        .Instance()
        .Calling(x => x.Index(null))
        .ShouldReturn()
        .Ok(x =>
        {
            x.ShouldPassForThe<MainLayout>(x => x.ParagraphTop.Contains("<h1>About Us</h1>"));
        });
    }
}

Environment:

  • OS: Windows
  • ASP.Net 5 MVC
  • Include="Microsoft.EntityFrameworkCore" Version="5.0.11"
  • <TargetFramework>net5.0</TargetFramework>
  • Include="MyTested.AspNetCore.Mvc" Version="5.0.0"

amunim avatar Jan 19 '22 10:01 amunim