简体   繁体   中英

basic assertions about unit testing

Given the function below - would I be able to assert if the Value "value" was deleted from the user? Or is that assertion part of the tests on the UserService?

Also, what assertions could I test from the function?

    public IHttpActionResult Post(string value)
    {
        var user = authorizationService.GetCurrentUser();

        var isDeleted = userService.DeleteValue(value, user);
        if (!isDeleted)
        {
            return NotFound();
        }

        userService.DeleteProperty(value, user);

        var identityResult = userService.Update(user);
        if (identityResult.Succeeded)
        {
            return Ok();
        }

        return InternalServerError();
    }

Yes, you can test that: a unit test doesn't have to be the smallest possible unit per sé but that it may also contain another unit inside of it. By writing tests for both these scenarios you're essentially making a layered project where you have separate tests for the different layers and the value they add to your chain.

You could make the analogy with VAT in a production chain where each test will test the value added in each segment. More information on that here .

This translates to your question as: yes, you can (and should) test whether this action method does what it is supposed to do.

A few examples of tests you could do:

  • value is null
  • value is not in the expect format (numeric, negative value, special characters)
  • The user is not found
  • a valid value will display Ok()

What you will have to do is make sure that you are not testing against a production database but instead use in-memory repositories (mocking, faking, stubbing, seaming, you name it).

By having these tests in your controller and inside your userService you will know the exact location of the problem in case it isn't working as you want it to:

Test for:   Controller           Service              Conclusion
            Works                Works                Works
            Works                Doesn't work         Faulty tests
            Doesn't work         Works                Controller test failed
            Doesn't work         Doesn't work         Service test failed

While not writing a test for the controller but instead relying on the service would not give you the information that your code actually works.

The line between unit-testing and other types (integration and acceptance testing mainly) is thin because you're testing a bigger part of the system but I still consider it unit-testing since it is contained to the logic of your application and does not use any external resources (database calls get mocked/stubbed/...).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM