I'm trying to create unit test for one of my method using MS test and Moq. Below is my interface, implementation class and method.
public interface IDocumentManagementHandler
{
Task AddData(long documentId, string metadataCategoryName, List<KeyValuePair<string, string>> metadata);
}
public class DocumentManagementHandler : IDocumentManagementHandler
{
private readonly IService _service;
private readonly IFService _fService;
public readonly ILogger _logger;
private static readonly long rootFolderId = 123456;
public DocumentManagementHandler(IService Service, IFService FService, ILogger Logger)
{
_service = Service;
_fService = FService;
_logger = Logger;
}
public Task AddData(long documentId, string metadataCategoryName, List<KeyValuePair<string, string>> metadata)
{
if(string.IsNullOrEmpty(metadataCategoryName))
throw new ArgumentNullException(nameof(metadataCategoryName));
if (metadata == null)
throw new ArgumentNullException(nameof(metadata));
return AddDocumentMetadataAsync(documentId, metadataCategoryName, metadata);
}
My MSTest method
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void TestAddData()
{
long documentID = 123;
string metadataCategoryName = null;
List<KeyValuePair<string, string>> metadata = null;
var documentHandler = new Mock<IDocumentManagementHandler>();
documentHandler.Setup(s => s.AddData(documentID, metadataCategoryName, metadata));
var newresult = documentHandler.Object.AddData(documentID, metadataCategoryName, metadata);
}
I'm expecting the test method to pass when I pass the variable "metadataCategoryName" as NULL but test is failing with the message "Test method did not throw expected exception System.ArgumentNullException." .
Any idea what's wrong here.
CodePudding user response:
Your issue: you are using a mock representing an interface of the object containing the method you want to test, which means your code is never really called (a breakpoint would have revealed this particular issue).
As for how you should have written your test :
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void TestAddData()
{
long documentID = 123;
string metadataCategoryName = null;
List<KeyValuePair<string, string>> metadata = null;
// Configure as needed using Mock.Get()
var service = Mock.Of<IService>();
var fService = Mock.Of<IFService>();
var logger = Mock.Of<ILogger>();
var documentHandler = new DocumentManagementHandler(service, fService, logger);
documentHandler.AddData(documentID, metadataCategoryName, metadata);
}
Additionally, you might want to assert the data contained in your exception. E.g. To check that your ArgumentNullException
is reporting the correct parameter name