lundi 29 février 2016

Verifying if a void method has been called using Moq

I have a class which is responsible for building PPT slides for exporting. To unit test this I have created an interface so it can be mocking using Moq; all great so far. However I run into difficulties when trying to test that my method has been called. It is a void method so at this point I only want to know that the method has been hit.

Here is my interface:

interface IPowerpointExporter
{
    void AddSlides(int amount);

    void setTitle(string title);
}

And here's my unit test:

[TestMethod]
public void testPPTObject()
{
    var mockPPT = new Mock<IPowerpointExporter>();
    mockPPT.Setup(m => m.AddSlides(1)).Verifiable();
    mockPPT.Object.AddSlides(1);
    mockPPT.VerifyAll();
}

However when I come to call AddSlides() I get a GeneratorException. The explanation for this is that my IPowerpointExporter was not accessible. I have a feeling this is because I am trying to call a method on an interface, though I'm unsure since I've got my object at mockPPT.Object.AddSlides(); at this point.

Note that I've also tried the following trying to use an actual object rather than Interface.Object. This also gives the same exception:

[TestMethod]
public void testPPTObject()
{
    var mockPPT = new Mock<IPowerpointExporter>();
    mockPPT.Setup(m => m.AddSlides(1)).Verifiable();

    ExportPowerPoint temp = (ExportPowerPoint)mockPPT.Object;
    temp.AddSlides(1);
    mockPPT.VerifyAll();
}

Using Moq how can I check that my method has been called? Is what I'm doing above along the right lines?

Aucun commentaire:

Enregistrer un commentaire