views:

199

answers:

2

I'm looking for some basic examples of using NMock2 to mock database calls for a CRUD application.

Thanks,

Chris

+1  A: 

Setup:

    [SetUp]
    public void SetUp()
    {
        mocks = new Mockery();
        mockDBLayer = _mocks.NewMock<IDBLayer>();

        //Inject the dependency somehow
        sut = new SUT(_mockDBLayer );
    }

Test:

    [Test]
    public void testMethodName_TestCase()
    {
        var dbRetrunValue = //whatever type
        Expect.Once.On(mockDBLayer).Method("dbMethod").Will(Return.Value(dbRetrunValue));

        //exercise
        var actual = sut.methodName();

        //Assert
        ...
    }

Verification if you want it

    [TearDown]
    public void TearDown()
    {
        mocks.VerifyAllExpectationsHaveBeenMet();
    }

I like Moq better however: http://code.google.com/p/moq/

Seth
+1  A: 

"database calls" is a rough term to guess at - do you mean testing your DAL, or testing a layer above that?

If you mean testing your DAL, you need to look at how you're getting the actual DataReader or DataTable, or whatever, so that you can replace it with the mock.

See blog posts like this that covers IoC and mocking data access , or posts like this that cover mocking a datareader for getting started.

Philip Rieck