My service class which have interface and injected service.
public class SomeService
{
private readonly ICustomConfigManager _customConfigManager;
private readonly IList<DefaultRoleSetting> _defaultRoleSettings;
public FCCLicenseTrackerService(ICustomConfigManager customConfigManager)
{
_customConfigManager = customConfigManager;
_defaultRoleSettings = customConfigManager.DefaultRoleSettings;
}
public async Task<List<CustomModel>> GetRequests(string Id)
{
var defaultRoleSetting = _defaultRoleSettings.FirstOrDefault(roleSetting => roleSetting.RoleId == Guid.Parse(GroupHelper.Name));
ValidateDefaultSettings(defaultRoleSetting);
return customReq;
}
My service method to which I have to make unit test case.
public async Task<List<CustomModel>> GetRequests(string Id)
{
var defaultRoleSetting = _defaultRoleSettings.FirstOrDefault(roleSetting => roleSetting.RoleId == Guid.Parse(GroupHelper.Name));
ValidateDefaultSettings(defaultRoleSetting);
return customReq;
}
private void ValidateDefaultSettings(DefaultRoleSetting defaultRoleSetting)
{
if (defaultRoleSetting == null)
{
throw new ArgumentException($"{nameof(defaultRoleSetting)} is null");
}
if (string.IsNullOrWhiteSpace(defaultRoleSetting.Name))
{
throw new ArgumentException($"{nameof(defaultRoleSetting.Name)} is null or empty");
}
if (string.IsNullOrWhiteSpace(defaultRoleSetting.Email))
{
throw new ArgumentException($"{nameof(defaultRoleSetting.Email)} is null or empty");
}
}
}
I am new to unit test case, as I gone through on web, didn't get any solution which is mock internal method, so due to it I am struck when 'defaultRoleSetting' is null pass. so any one can share sample code to mock for 'var defaultRoleSetting'.
What I have tried:
my test code is
public async Task GetRequests_SendingValidId_ExpectedReturnObjectType()
{
var fakeDefaultReq = FakeDefaultRoleSetting();
_mockCustomConfigManager.Setup(s => s.DefaultRoleSettings).Returns(fakeDefaultReq);
var service = this.CreateService();
string Id = "2";
var expected = JsonConvert.DeserializeObject<IList<JObject>>(GetFakeRequests());
var result = await service.GetRequests(Id);
Assert.Equal(JsonConvert.SerializeObject(result), JsonConvert.SerializeObject(expected));
}
fake object method for mock dependency injection.
private List<DefaultRoleSetting> FakeDefaultRoleSetting()
{
string fakeData = @"[{
'RoleId': '00000000-0000-0000-0000-000000000000',
'Name': null,
'Email': null,
'UserId': '00000000-0000-0000-0000-000000000000'
}]";
return JsonConvert.DeserializeObject<List<DefaultRoleSetting>>(fakeData);
}
fake object method for return match.
private string GetFakeRequests()
{
string fakeData = @"[{
'userId': '00000000-0000-0000-0000-000000000000',
'StatusId': 0.0,
'createdOn': '0001-01-01T00:00:00',
'createdBy': '00000000-0000-0000-0000-000000000000',
'modifiedOn': null,
'modifiedBy': null,
'buildoutCompletedDate': null,
'buildoutDeadlineReason': null
}]";
return fakeData;
}