简体   繁体   中英

How to unit test void method of web api controller

I have a void method in controller which insert data to local database. How can i do a integration test on that method.

I have tried this so far and don't know what to add in assert.

 [TestMethod]
    public void ProcessTransactions()
    {
        // Arrange
        _transactionController = new TransactionController(_transactionService, _mService);

        // Act
        _transactionController.ProcessTransactions;

        // Assert
    }

Is it possible that you may be able to change the method to return a bool?

public bool TryProcessTransactions() 
{
     bool wasGreatSuccess = false;

     // do work

     return wasGreatSuccess; 
}

Else, I guess you could retrieve from the database whatever was supposed to be inserted and Assert.IsEqual() .

You have a few options, depending on what you want to test and how deeply you want to test it.

  1. If you want to check your controller interaction with it's dependencies, you can use a mock (eg mock your _transactionService ) and assert what methods were called on the mock, with what parameters, etc. I personally do not recommend this type of tests though. They make your code very refactoring-resistant. It doesn't really test what your app does, but rather how your app does it, which makes little sense to me.
  2. You can run your tests on the real implementations of your classes (no mocks). Then you should focus on verifying the system state (eg what's in the database) after the tested method execution. This kind of tests worked better for me, but they require you to setup a database first with some seed data, which could be a big hassle in a large system. These test run slowly, due to database communication and especially due to the need of arranging a database state beforehand.
  3. You can also skip the test of the controller, or do it very sketchily and focus on testing your domain logic. It's still good to throw a few simple tests just to verify whether your controllers work at all.

There's no definite answer to this question. It all "depends", but I hope I threw some light on possibilities.

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