Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a method as parameter without declaring a delegate in .NET

No matter how I try, I cannot mimic the clean syntax of Rhino Mocks, without declaring a delegate.

Example:

Expect.Call(service.HelloWorld("Thanks"))

Do you have any idea on how to do this?

Thanks.

like image 572
Marc Vitalis Avatar asked Mar 07 '26 08:03

Marc Vitalis


2 Answers

You could use the Action delegate provided in newer versions of .NET

void Execute(Action action) {
    action();
}

void Test() {
    Execute(() => Console.WriteLine("Hello World!"));
}
like image 59
sisve Avatar answered Mar 09 '26 00:03

sisve


Using Lambda syntax in 3.5 you can get a similar syntax.

public void Call(Action action)
{
    action();
}

Expect.Call(() => service.HelloWorld("Thanks"));

Moq is a mocking framework that uses Lambda syntax for it's mocking.

var mock = new Mock<IService>();
mock.Setup(service => service.HelloWorld("Thanks")).Returns(42);
like image 35
Cameron MacFarland Avatar answered Mar 08 '26 23:03

Cameron MacFarland