How to write unit test for a service that is dependent on another service or database

Sorry if I ask a very simple question,

I have a set of web services (developed using .Net WebApi). These services are the access level or data access level APIs. These APIs either depend on other services or the database itself.

I want to write a unit test for it. I have the following questions.

  • Because business-level APIs are dependent on a data access service or some other service. If I write unit test only to call the business API, it will call the data access API. Is this the correct way to write unit test case? or should I enter the whole dependency object using unit test? I think it used to be an integration test, not a unit test.

  • Should I write unit tests for the data access layer? I checked this link ( Writing tests for a data access code: unit tests are waste ) and it says that DAL does not require unit tests. Do I have to write tests for the data access level. I think this will be an integration test, not unit tests?

+5
source share
1 answer

Question 1:

I would say if you want to do TDD, then this is not the "right" way, because, as you said, you will perform integration tests. Again, perhaps you do not want to do TDD, and the integration tests are good enough for you, but to answer the question: this will not be the right way ** unit - ** to check your code.


Question 2

I would say that it depends on what you have at your level of data access. For example, if you are implementing repositories, you probably want to write some tests.

Save method

You want to make sure that, provided that the object that you extracted from your repository has edited some properties of this object and saved the changes, it will actually save the changes and will not create a new object. Now: you might think that this is an integration test, but it really depends on how well your code is designed. For example, your repository might just be an extra layer of logic on top of a low-level ORM. In this case, when testing the save method, what you will do is that you will argue that the correct methods are called with the correct parameters in the ORM service entered into your repository.

Errors and Exceptions

There may be problems accessing the data, such as connecting to a broken database, or the data format is not as expected, or problems of deserialization. If you want to ensure good error handling and possibly create custom exceptions and add additional information to them depending on the context, then you definitely want to write tests to make sure that the correction information is distributed

, on the other hand

If your DAL is just a few classes that wrap the unthinkable ORM and you don’t have any logic there, then you probably don’t need tests, but it seems like this does not happen too often, you will almost always have some logic, which may go wrong and what you want to test.

0
source

Source: https://habr.com/ru/post/1234123/


All Articles