开发者

Does this test really add value...?

As I'm writing tests for a simple asp.net mvc 3 app, I noticed something about a test I've written blindly in the past.

[TestMethod]
public void Add_Saves_Object()
{
    var rep = new Mock<IRepository>();
    rep.Setup(x => x.Save<Object>(It.IsAny<Object>())).Returns(new Object() {Id = 1});

    var pick = rep.Object.Save<Pick>(new Object());

    Assert.IsNotNull(pick);
    Assert.AreEqual(1, pick.Id);
}

The assumption here is that I've tested my IRepository implementation again开发者_如何学JAVAst an "in-memory" data store, and the Save method correctly returns an object (As I am mocking my repository). Being that my repository tests are passing successfully, do I need to test that my controller correctly calls the repository and receives an object back from the save method? Does this test add value? Is it worth the time to write it?

If I add in a curve to this scenario, i.e. the SaveObject method on my controller redirects to another action, how would I test the redirect?


Nope.

In this scenario you're testing that you wrote your test correctly.

Testing with in-memory repositories is usually bad in general if you're using any type of RDBMS because unless you replicate all of the data and relationship constraints its very easy to write tests against scenarios which would never happen in production.

Now this is contentious but this type of test is almost useless because its likely your application won't even run without this piece of logic working. All of your integration tests will also fail if this piece of logic fails. That's good enough for me.


It looks like the only thing this test is testing is that your mocking framework is set up correctly. I would say there's minimal value in such a test.

To try and answer your second question, if your SaveObject method redirects to another action, say X, I would think you would want to test that some public action on some other mock was performed by X. It's hard to be more specific without more details.


If you want to test your repository, you shouldn't mock it. Instead, mock its dependencies.

For testing redirects tryout mvccontrib Test Helper. With it you could do something like this:

        [Test]
        public void RedirectToIndex()
        {
            SomeController controller = new SomeController();
            ActionResult result = controller.Index();
            result.AssertActionRedirect().ToAction("Index");
        }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜