tags:

views:

285

answers:

3

How can i test that a particular method was called with the right parameters as a result of a test? I am using nunit.

The method doesn't return anything. it just writes on a file. I am using a moq object for System.IO.File. So I want to test that the function was called or not.

+1  A: 

You have to use some mocking framework, such as Typemock or Rhino Mocks, or NMocks2.

NUnit also has a Nunit.Mock, but it is not well-known.

The syntax for moq can be found here:

var mock = new Mock<ILoveThisFramework>();

// WOW! No record/reply weirdness?! :)
mock.Setup(framework => framework.DownloadExists("2.0.0.0"))
    .Returns(true)
    .AtMostOnce();

// Hand mock.Object as a collaborator and exercise it, 
// like calling methods on it...
ILoveThisFramework lovable = mock.Object;
bool download = lovable.DownloadExists("2.0.0.0");

// Verify that the given method was indeed called with the expected value
mock.Verify(framework => framework.DownloadExists("2.0.0.0"));

Also, note that you can only mock interface, so if your object from System.IO.File doesn't have an interface, then probably you can't do. You have to wrap your call to System.IO.File inside your own custom class for the job.

Ngu Soon Hui
NUnit just runs tests, it doesn't do mocking or verification. Different responsibilities. You should be able to verify the expectations on your mock object, though I haven't used Moq.
kyoryu
yep i was looking at the wrong place... I was looking in nunit. now i am looking at moq. :)
Umair Ahmed
MOQ will allow you to mock abstract classes too.
Paul Hadfield
+2  A: 

By using a mock for an interface.

Say you have your class ImplClass which uses the interface Finder and you want to make sure the Search function gets called with the argument "hello";

so we have:

public interface Finder 
{
  public string Search(string arg);
}

and

public class ImplClass
{
  public ImplClass(Finder finder)
  {
    ...
  }
  public void doStuff();
}

Then you can write a mock for your test code

private class FinderMock : Finder
{
  public int numTimesCalled = 0;
  string expected;
  public FinderMock(string expected)
  {
    this.expected = expected;
  }
  public string Search(string arg)
  {
    numTimesCalled++;
    Assert.AreEqual(expected, arg);
  }
}

then the test code:

FinderMock mock = new FinderMock("hello");
ImplClass impl = new ImplClass(mock);
impl.doStuff();
Assert.AreEqual(1, mock.numTimesCalled);
tster
+2  A: 

More context is needed. So I'll put one here adding Moq to the mix:

pubilc class Calc {
    public int DoubleIt(string a) {
        return ToInt(a)*2;
    }

    public virtual int ToInt(string s) {
        return int.Parse(s);
    }
}

// The test:
var mock = new Mock<Calc>();
string parameterPassed = null;
mock.Setup(c => x.ToInt(It.Is.Any<int>())).Returns(3).Callback(s => parameterPassed = s);

mock.Object.DoubleIt("3");
Assert.AreEqual("3", parameterPassed);
Dmytrii Nagirniak