Documentation

Create a unit test

Add a unit test to your project using dependency injection patterns.
Read time 1 minuteLast updated a day ago

The following example tests the
TestInjection
Cloud Code method from the dependency injection guide. This example uses two separate mock instances of
IRandomNumber
. The first instance is injected through the class constructor, and the other instance is passed directly to the method. This example verifies that both injection points work correctly. The two instances use different values (
1
and
2
) so that you can identify which injection point failed if the assertion doesn't pass.
using ExampleModule;using NUnit.Framework;namespace TestExampleModule;public class MockedRandomNumber : IRandomNumber{ public int Number; public MockedRandomNumber(int number) { Number = number; } public int GetRandomNumber() { return Number; }}public class Tests{ private MockedRandomNumber mockedRandomNumberA; private MockedRandomNumber mockedRandomNumberB; [SetUp] public void Setup() { mockedRandomNumberA = new MockedRandomNumber(1); mockedRandomNumberB = new MockedRandomNumber(2); } [Test] public void TestDependencyInjection() { TestDependencyInjection dependencyInjection = new TestDependencyInjection(mockedRandomNumberA); DependencyInjectionResult result = dependencyInjection.TestInjection(mockedRandomNumberB); Assert.AreEqual(new DependencyInjectionResult { ConstructorNumber = mockedRandomNumberA.Number, MethodNumber = mockedRandomNumberB.Number, }, result, "Values are not the same"); }}
Run the unit test according to your IDE and confirm that the test passes. Refer to Unit testing C# with NUnit and .NET Core (Microsoft) for more information. To avoid publishing excess binaries when creating unit tests, refer to Create a unit test project.