0

We are trying the Test Driven Development using Fluent Assertions for our .Net core 3.1 Web API and using XUnit for the same.

This is what my controller returns.

{
    "usersResult": [
       {
       "UserId": "1",
       "UserName": "Foo"
        },
        {
        "UserId": "2",
        "UserName": "Boo"
        }
    ]

}

In my test method, I want to check if it returns an object, i.e. I want to assert on the userResult Type, when I debug its showing anonymous type for "userResult" , so I am confused to what type should I specify in : Should().BeOfType(??)

[HttpGet]

        public async Task<IActionResult> GetUsers()
        {
    
        Users us = new Users();
        var us = await _service.GetUsers();
                          
        return Ok(new { usersResult = us });
        
        }


public class Users 
{
 public string UserId{ get; set; }
 public string UserName{ get; set; }
}

// TestMethod :

  [Fact]
  public async Task GetUsers_OnSuccess_ReturnsListOfUsers()
        {
            var sut = new UserController();
            var result = await sut.GetUsers();

            result.Should().BeOfType<OkObjectResult>();
            var objectResult = (OkObjectResult)result;
           
            objectResult.Value.Should().BeOfType<**WHAT_To_Specify**>();
        }
Ann Snow
  • 63
  • 1
  • 7

2 Answers2

0

You shouldn't directly test your controller classes. You should create an in-memory test server and then invoke real HTTP requests like this.

Dennis Doomen
  • 8,368
  • 1
  • 32
  • 44
0

in TDD its better to apply separation of concern and DIP ( Dependency Inversion Principle) in your project , the Controller Responsible for Receiving Requests and Send them to the Services , so it doesn't have any logic inside .

in most situations we use unit testing to make sure a peace of logic working well.

its not recommended to use it in places which have two or more layers of abstraction ,

you need to isolate the SUT(System under Test)from required abstractions like repositories.

For Example : when you are using Repository Pattern in your project and call repository methods in your services , Its Better to use Mock , Fake or Stub to Create a fake instance of repository interface and return your favorite result from it . this is what we call it unit test .

the test you are trying to have it is called Integration Testing . and Its Not Recommended to use it between Controller and Service .

we usually use it to make sure the interaction between database and project is completely fine.

I Suggest to Ignore this part and don't test it in this way . but if you want to test it :

its better to use Behavior Testing(API Testing) with specflow which is Test Hole Operation from API to Database .

Javid_Leo
  • 1
  • 1