I would like to create unit test for my C# application. There are the functions which create objects inside and perform some checks on the created object. Since I want it to be unit test, functions should be separated from the object dependencies. Is there a way to mock objects created inside the function?
In the following code block, DeviceManager class is under unit test and ConnectWirelessDeviceToSystem unit is tested. However, function code block depends the creation of WirelessDevice object which needs to be mocked.
public class DeviceManager
{
public async Task ConnectWirelessDeviceToSystem(ushort unitId)
{
WirelessDevice wirelessDevice = _devices.FirstOrDefault(x => x.Key == unitId).Value.WirelessDevice;
if (wirelessDevice == null)
{
return;
}
if (wirelessDevice.HasSerialNumber)
{
Console.WriteLine("Device has serial number {0}", wirelessDevice.GetSerialNumber());
}
else
{
Console.WriteLine("Device does not have serial number, can not connect to system");
}
}
}
I have tried using Moq framework but could not achieve mocking object created in the function.
Hamza is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1