tags:

views:

247

answers:

2

I'm using Moq library. I'm mocking up an instance that does all regular CRUD functionality. I would like to set it up in a way to allow only one Delete(x) call over some object and all consecutive calls to Delete(x) of the same object should return an Exception.

My Delete() method returns void.

How do I do that?

Some code

mock = new Mock<ITest>();
mock.Setup(m => m.Delete(1));
mock.Setup(m => m.Delete(3)).Throws<Exception>();
...
A: 

can't you do something like (exact syntax may be off from memory):

mock.Expect(m => m.Delete(1)).Times.Exactly(1);
Joel Martinez
Expect is now obsolete and "Setup" should be used instead. But There's no Times method/property I could call... :(
Robert Koritnik
+1  A: 

Let the code talk :-)

    public interface ITest
    {
        void Delete(int x);
    }

    [TestMethod]
    [ExpectedException(typeof(InvalidOperationException))]
    public void TestMethod1()
    {
        HashSet<int> deleted = new HashSet<int>();

        var mock = new Mock<ITest>();
        mock.Setup(m => m.Delete(It.Is<int>(x => deleted.Contains(x))))
            .Throws(new InvalidOperationException("already deleted"));
        mock.Setup(m => m.Delete(It.Is<int>(x => !deleted.Contains(x))))
            .Callback<int>(x => deleted.Add(x));

        mock.Object.Delete(1);
        mock.Object.Delete(1);
    }
Yacoder
very nice trick in did.
Robert Koritnik