The test method should follow the naming convention [MethodUnderTest]_[BehaviourToTest]_[ExpectedResult].
Example: A method named GetProduct should be tested to see if it returns an existing product.
The name of the test should be GetProduct_ProductExist_ProductReturned:
A unit test should only test its assigned layer. Any lower layer that requires/interacts with external resources should be mocked to ensure sure that the unit tests are idempotent.
Note
Example: We want to implement unit tests for a controller that requires three services. Each service depends on other services/repositories/http clients that need external resources like databases, APIs...
Any execution of unit tests that depend on these external resources can be altered (not idempotent) because they depend on the uptime and data of these resources.
On the IoT Hub portal, we use the library Moq for mocking within unit tests:
[TestFixture]publicclassProductControllerTests{privateMockRepositorymockRepository;privateMock<IProductRepository>mockProductRepository;privateIProductServiceproductService;[SetUp]publicvoidSetUp(){// Init MockRepository with strict behaviourthis.mockRepository=newMockRepository(MockBehavior.Strict);// Init the mock of IProductRepositorythis.mockProductRepository=this.mockRepository.Create<IProductRepository>();// Init the service ProductService. The object mock ProductRepository is passed the contructor of ProductServicethis.productService=newProductService(this.mockProductRepository.Object);}[Test]publicasyncTaskGetProduct_ProductExist_ProductReturned(){// ArrangevarproductId=Guid.NewGuid().ToString();varexpectedProduct=newProduct{Id=productId};// Setup mock of GetByIdAsync of the repository ProductRepository to return the expected product when given the correct product id_=this.mockProductRepository.Setup(repository=>repository.GetByIdAsync(productId)).ReturnsAsync(expectedProduct);// Actvarproduct=this.productService.GetProduct(productId);// Asset_=product.Should().BeEquivalentTo(expectedProduct);// Assert that all mocks setups have been called_=MockRepository.VerifyAll();}}