I am doing Test Case with using Moq Framework. For below Repository Test cases i am receiving null value after setting up Proper Setup.I Shouldn't know that this type of repos code mocking is Possible Or not.Any Help Appreciated. .
public class DocumentRepository : IDocumentRepository
{
private IDataSourceFactory director;
private IDataSourceRepository dataSourceRepository;
private IDocumentResourceRepository documentSourceRepository;
private IConfiguration configuration;
private ICryptography<string> cryptography;
private readonly IMapper mapper;
public DocumentRepository(IDataSourceFactory _director, IConfiguration _configuration, ICryptography<string> _cryptography, IMapper _mapper)
{
director = _director;
dataSourceRepository = _director.GetDataSourceRepository(Enums.DataSourceType.SQL)();
documentSourceRepository = _director.GetDocumentResourceRepository(Enums.DataSourceType.SQL)();
configuration = _configuration;
cryptography = _cryptography;
mapper = _mapper;
}
/// <inheritdoc/>
public async Task<(byte[]?, string)> GetFileContentAsync(string resource_id)
{
//get file by resource_id
var documentLinkStr = cryptography.Decrypt(HttpUtility.UrlDecode(resource_id)?.Trim()?.Replace(" "," "));
var documentLink = JsonConvert.DeserializeObject<DocumentLink>(documentLinkStr);
if (documentLink is null)
throw new Exception("Invalid Resource Id");
documentSourceRepository = director.GetDocumentResourceRepository((Enums.DataSourceType)Enum.Parse(typeof(Enums.DataSourceType),
documentLink.DocumentSource))();
return await documentSourceRepository.GetDocument(documentLink);
}
}
This is below is My Test Cases Class:
public class DocumentRepositoryTests
{
private readonly Mock<IDataSourceFactory> _dataSourceFactoryMock;
private readonly Mock<IDataSourceRepository> _dataSourceRepositoryMock;
private readonly Mock<IDocumentResourceRepository> _documentSourceRepositoryMock;
private readonly Mock<IConfiguration> _configurationMock;
private readonly Mock<ICryptography<string>> _cryptographyMock;
private readonly Mock<IMapper> _mapperMock;
private IDocumentRepository? documentRepository;
//string[] demoData;
public DocumentRepositoryTests()
{
_dataSourceFactoryMock = new Mock<IDataSourceFactory>(MockBehavior.Strict);
_dataSourceRepositoryMock = new Mock<IDataSourceRepository>();
_documentSourceRepositoryMock = new Mock<IDocumentResourceRepository>();
_configurationMock = new Mock<IConfiguration>();
_cryptographyMock = new Mock<ICryptography<string>>();
_mapperMock = new Mock<IMapper>();
}
[Fact]
public void If_validResourceIdValue_Pass_GetDocumentAsync_Return_FilesByteArraysAndFileName()
{
//Arrange
string validResourceIdValue = "1234567";
DocumentLink documentLink = new DocumentLink("1B2F00DD-3A2D-4F17-A9EF-50709ABD9932", "SQL", "DocumentId1");
string documentLinkString = JsonConvert.SerializeObject(documentLink);
string fileName = "Demo.pdf";
string demoData =
@"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Porta non pulvinar
neque laoreet suspendisse. Turpis in eu mi bibendum. Aliquam ut
porttitor leo a diam sollicitudin. Faucibus interdum posuere lorem ipsum
dolor sit. Congue eu consequat ac felis donec et odio. Bibendum arcu
vitae elementum curabitur vitae nunc sed velit. Convallis tellus id
interdum velit laoreet. Sollicitudin tempor id eu nisl nunc mi ipsum
faucibus vitae. Justo donec enim diam vulputate ut pharetra sit. Proin
sed libero enim sed faucibus. Ornare quam viverra orci sagittis eu. Odio
ut enim blandit volutpat maecenas volutpat blandit. Erat velit
scelerisque in dictum non consectetur a.
Morbi enim nunc faucibus a. Varius morbi enim nunc faucibus a
pellentesque sit. Urna duis convallis convallis tellus id interdum velit.
Dictumst quisque sagittis purus sit. Praesent tristique magna sit amet
purus gravida. Aliquam eleifend mi in nulla. Fringilla phasellus faucibus
scelerisque eleifend donec pretium vulputate. Mi bibendum neque
egestas congue quisque egestas. Facilisis leo vel fringilla est ullamcorper.
Ornare lectus sit amet est placerat in egestas erat imperdiet. Orci a
scelerisque purus semper eget. Tortor posuere ac ut consequat semper
viverra nam libero. Parturient montes nascetur ridiculus mus.";
byte[] demoBytes = Encoding.UTF8.GetBytes(demoData);
var dataSourceRepositoryMock = Mock.Of<Func<IDataSourceRepository>>();
_dataSourceFactoryMock.Setup(p => p.GetDataSourceRepository(It.IsAny<Document.Domain.Shared.Enums.DataSourceType>())).Returns(dataSourceRepositoryMock);
//var documentResourceRepository = Mock.Of<Func<IDocumentResourceRepository>>(MockBehavior.Strict);
var documentResourceRepository = Mock.Of<Func<IDocumentResourceRepository>>();
_dataSourceFactoryMock.Setup(p => p.GetDocumentResourceRepository(It.IsAny<Document.Domain.Shared.Enums.DataSourceType>())).Returns(documentResourceRepository);
//Mock.Get(documentResourceRepository).Setup(s => s.Invoke()).Returns(documentResourceRepository);
//_dataSourceFactoryMock.SetupSequence(p => p.GetDocumentResourceRepository(It.IsAny<Document.Domain.Shared.Enums.DataSourceType>()))
// .Returns(documentResourceRepository)
// .Returns(documentResourceRepository);
_cryptographyMock.Setup(p => p.Decrypt(It.IsAny<string>())).Returns(documentLinkString);
_documentSourceRepositoryMock.Setup(p => p.GetDocument(documentLink)).ReturnsAsync((demoBytes, fileName));
documentRepository = new DocumentRepository(_dataSourceFactoryMock.Object, _configurationMock.Object, _cryptographyMock.Object, _mapperMock.Object);
//Act
var response = documentRepository.GetFileContentAsync(validResourceIdValue).Result;
//Assert
Assert.True(response.Item1 == demoBytes);
Assert.True(response.Item2 == fileName);
}
but this line always return null after proper Mock Setup then also:
documentSourceRepository = director.GetDocumentResourceRepository((Enums.DataSourceType)Enum.Parse(typeof(Enums.DataSourceType),
documentLink.DocumentSource))();
Can this Methods test case with Moq Possible?
CodePudding user response:
First setup the IDocumentResourceRepository
mock
var repoMock = Mock.Of<IDocumentResourceRepository>();
repoMock
.Setup(r => r.GetDocument(It.IsAny<DocumentLink>())
...
Then setup the GetDocumentResourceRepository
method's mock
- it returns a function which returns the
IDocumentResourceRepository
mock
dataSourceFactoryMock
.Setup(p => p.GetDocumentResourceRepository(It.IsAny<DataSourceType>()))
.Returns(() => repoMock.Object);
UPDATE #1
This is the fine-tuned version of the above code (changes made by @Dipak Rathod)
_documentSourceRepositoryMock
.Setup(p => p.GetDocument(It.IsAny<DocumentLink>()))
.ReturnsAsync(()=>(demoBytes, fileName));
_dataSourceFactoryMock
.Setup(p => p.GetDocumentResourceRepository(It.IsAny<Document.Domain.Shared.Enums.DataSourceType>()))
.Returns(() => _documentSourceRepositoryMock.Object);