Consider a scenario where a developer needs to create a unit test for a method that generates a new GUID string (or any new object):
public string GetNewGuid()
{
return Guid.NewGuid().ToString();
}
A junior developer might initially write a test like this:
[Fact]
public void GetNewGuid_VerifyGuid()
{
Business business = new Business();
var expected = Guid.NewGuid().ToString();
var val = business.GetNewGuid();
Assert.Equal(val, expected);
}
However, this test will fail on the Assert line because it relies on a freshly generated GUID for each call.
So, what’s the solution when dealing with code that uses the new statement? One approach is to utilize a simple Func delegate. Start by creating a Func delegate:
internal Func<string> NewGuid = () => Guid.NewGuid().ToString();
Then, replace the usage of Guid.NewGuid().ToString(); with this delegate:
internal Func<string> NewGuid = () => Guid.NewGuid().ToString();
public string GetNewGuid()
{
return NewGuid();
}
Now, the trick is that you can inject your own implementation of NewGuid as needed. Here’s how you can modify the test:
[Fact]
public void GetNewGuid_ValidateGuid()
{
Business business = new Business();
var expected = Guid.NewGuid().ToString();
business.NewGuid = () => expected;
var val = business.GetGuidTestable();
Assert.Equal(val, expected);
}
By assigning a new implementation to NewGuid, you can control the output for testing purposes.
Additionally, ensure you add the following two lines to the AssemblyInfo.cs file of the source project:
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Business.Test")]
This allows access to internal members for testing purposes.
By employing this approach, developers can effectively create unit tests for code that involves the instantiation of new objects, enhancing the robustness and reliability of their software.