0

I am new to unit test. One thing I am struggling with is to determine what type of test to write for my method. Using the code below as an example, what should I be testing here? what are the various test I can write.

[HttpGet]
[Route("GetPosts")]
public async Task<IActionResult> GetPosts()
{
    try
    {
        var posts = await postRepository.GetPosts();
        if (posts == null)
        {
            return NotFound();
        }

        return Ok(posts);
    }
    catch (Exception)
    {
        return BadRequest();
    }
}
Nkosi
  • 235,767
  • 35
  • 427
  • 472
Baba
  • 2,059
  • 8
  • 48
  • 81

1 Answers1

0

In a unit test you test a very small piece of code, e.g. a method. It is important that the unit test only tests the code in the method you want to test. It does not test any dependencies. They have to be mocked (with Moq, for example).

I think you are dealing with three test cases (= three tests) here:

  1. Posts are found

  2. Posts are not found

  3. An exception occurs

It is important that the unit test does not call the actual repository. You have to mock it and simulate the GetPosts-method.

After you have implemented your unit tests you can think about implementing a few integration tests as well. The difference is that you include the actual repository in your tests.

Dharman
  • 30,962
  • 25
  • 85
  • 135