I have to unit test a function ( SendMessageNetSkyToAgenceGrp
), and inside this function there is a service that I want to mock ( EnvoyerNotificationSms.SendMessageNetSky(signalRMessage)
): Here is the code i want to test:
public void SendMessageNetSkyToAgenceGrp(
int agenceId,
string message,
string name,
bool addAgenceLibInMsg = true,
SignalRMessageThemeEnum theme = SignalRMessageThemeEnum.Information)
{
Agence agence = AgenceCoreService.GetAgenceById(agenceId);
if (agence == null || (string.IsNullOrEmpty(agence.Libelle) && addAgenceLibInMsg))
{
return;
}
string finalMessage = (message + (addAgenceLibInMsg ? agence.Libelle : ""));
string groupName = string.Empty;
if (theme == SignalRMessageThemeEnum.NotificationSms)
{
groupName = SignalRConstantes.GRP_SMSAGENCE + SignalRConstantes.SEPARATOR + agenceId;
}
else
{
groupName = (SignalRConstantes.GRP_AGENCE + SignalRConstantes.SEPARATOR + agenceId);
}
SignalRMessage signalRMessage = new SignalRMessage(name, "", finalMessage, groupName, theme);
EnvoyerNotificationSms.SendMessageNetSky(signalRMessage);
}
And here is the test code:
[Fact(DisplayName = "Vérifier l'appel à l'infra IEnvoyerNotificationSms")]
public void SendMessageNetSkyToAgenceGrp_CasNormal_ResultatOk()
{
// Arange
var envoyerNotificationSmMock = new Mock<IEnvoyerNotificationSms>();
envoyerNotificationSmMock.Setup(envoyerNotifSms => envoyerNotifSms.SendMessageNetSky(It.IsAny<SignalRMessage>())).Verifiable();
var SignalRCoreService = LocalIocManager.Resolve<ISignalRCoreService>();
// Act
LocalIocManager.IocContainer.UseInstance(envoyerNotificationSmMock.Object, IfAlreadyRegistered.Replace);
SignalRCoreService.SendMessageNetSkyToAgenceGrp(56, "testMessage", "name", true, SignalRMessageThemeEnum.NotificationSms);
// Assert
envoyerNotificationSmMock.Verify(envoyerNotifSms => envoyerNotifSms.SendMessageNetSky(It.IsAny<SignalRMessage>()), Times.Once());
}
But when I execute the test I get an error telling me that the service I want to mock is null ( EnvoyerNotificationSms.SendMessageNetSky(signalRMessage);
) The error is: 'Object reference not set to an instance of an object.' in the line EnvoyerNotificationSms.SendMessageNetSky(signalRMessage);
How can I solve this issue?
After checking the problem was the order of these lines:
var SignalRCoreService = LocalIocManager.Resolve<ISignalRCoreService>();
// Act
LocalIocManager.IocContainer.UseInstance(envoyerNotificationSmMock.Object, IfAlreadyRegistered.Replace);
In the second line has no effect, because the service i want to mock is already created in the first line. So the solution was to change the order of the two lines.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.