Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I assert that a particular method was called using NUnit?

Tags:

c#

tdd

moq

nunit

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 mock object for System.IO.File. So I want to test that the function was called or not.

like image 640
Umair Ahmed Avatar asked Dec 03 '09 05:12

Umair Ahmed


People also ask

How do you test if a method is called in NUnit?

You can verify using MOQ using the Verify method. Like this: var tokenManagerMock = new Mock<ITokenManager>(); var sut = new WhateverItIsCalled(tokenManagerMock. Object); sut.

How to Assert in NUnit?

NUnit Assert class is used to determine whether a particular test method gives expected result or not. In a test method, we write code the check the business object behavior. That business object returns a result. In Assert method we match the actual result with our expected result.

How do you mock a method in NUnit?

The three key steps to using mock objects for testing are: Use an interface to describe the object. Implement the interface for production code. Implement the interface in a mock object for testing.


1 Answers

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);
like image 187
Dmytrii Nagirniak Avatar answered Sep 22 '22 21:09

Dmytrii Nagirniak