0

Hi I am trying to write a simple unit test for a function.

That function is to get something from the Controller class and get a specific item from it.

This is the code that I wanted to do unit test from (In Helper class):

public static string GetMemberCode(Controller controller)
{
    var claim = controller.User.Claims.FirstOrDefault(c => c.Type == "membercode");
    return (claim != null) ? claim.Value : string.Empty;
}

The way this function is called is by using (More than 1 Controller class will be calling this)

string membercode = Helper.GetMemberCode(this)

This is what I have in my unit testing for now

[Theory]
[InlineData("asdfqwer")]
public void GetMemberCode_IfControllerIsValid(string membercode)
{
    //Arrange
    var controller = new Controller(); //ERROR:CS0144 Cannot create an instance of the abstract type or interface 'Controller'
    //TODO: How to assign value inside?
    //Act
    var result = Helper.GetMemberCode(controller);
    //Assert
    result.Should().Be(membercode);
}

So my question is How to assign value inside the Controller class?

Thanks in advance.

Zorev Gnoz
  • 221
  • 4
  • 20
  • Is your controller really the same name as its base class "Controller"? If so, you need the full namespace. – Jasen Mar 16 '22 at 03:03
  • My controller is MemberController : Controller While getting it its just string membercode = GetMemberCode(this) – Zorev Gnoz Mar 16 '22 at 03:05
  • The compiler error is because you are trying to instantiate the base abstract Controller class. – Jasen Mar 16 '22 at 03:07
  • is there any other way to do unit test on this? And how do i assign the value inside the Controller.User.Claims ? – Zorev Gnoz Mar 16 '22 at 03:07
  • `var controller = new MemberController();` https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/testing?view=aspnetcore-6.0 – Jasen Mar 16 '22 at 03:08
  • I cant do this method as due to this function is in a Helper class, and there are more than 1 controller will be calling this Helper class – Zorev Gnoz Mar 16 '22 at 03:09
  • I don't understand, you can pass the instance of MemberController to your helper function as it is a Controller. Have you seen the answers here discussing controller testing? https://stackoverflow.com/questions/8818207/how-should-one-unit-test-a-net-mvc-controller – Jasen Mar 16 '22 at 03:12
  • I have go thru the discussions but then I am not allowed to change the code in the Helper class, I just need to create unit testing for the helper class. I am unable to declare the Controller to MemberController as due to not just MemberController will be using it, AController, BController, CController will also be calling that Helper class function. – Zorev Gnoz Mar 16 '22 at 03:16

0 Answers0