user256034
user256034

Reputation: 4369

Unit test design question

I'd like to unit test this method

public string Edit(int id)
{
   var item = _repository.Get(id);

   string json = _jsonConverotr.Convert(item);

   return json;
}

The repository will by mocked. But the jsonConvertor is a simple class to convert an entity to json.

So my question is,should I also mock the jsonConvertor class or is it Ok to use the original ? The jsonConvertor class is tested elsewhere.

Upvotes: 3

Views: 488

Answers (4)

Brian Geihsler
Brian Geihsler

Reputation: 2087

A helpful way to think about this here is: what behavior are you trying to test? The behavior you're after is that given a valid id, return the JSON'd object. I would recommend one of the two following approaches, both of which don't mock the JSON conversion:

  1. Handcraft the JSON as your expected result and assert that it equals the returned value. The fact that you're using the JsonConverter is an implementation detail. Your test shouldn't care about how it gets the JSON. It should just care that it gets valid JSON.
  2. Create a class named JSONResult that has an Object property and a ToJSON() method. Then your method could return a JSONResult and you could assert that its Object property equals the object you returned from your mock repository. Then you can have separate tests to make sure ToJSON works correctly. (Also, this method looks strikingly like an ASP.NET MVC method on a Controller, which means you should use the built in JSONResult that derives from ActionResult)

Thinking about this, I'd recommend #2. It's cleaner to test and more descriptive about what's going on.

Upvotes: 2

Peter
Peter

Reputation: 27944

If you have test for you jsonConverter, then you should mock it. Only test the Edit method and check if the calls and results are as you expect.

The reason to mock it is that if there is a bug in the jsonConverter and this test fails you do not know where to look for the bug. If your jsonConverter is test well enough, it will show in one of the jsonConverter tests. And you know where to look and fix the bug.

Upvotes: 4

maple_shaft
maple_shaft

Reputation: 10463

I don't see the point in a unit test for this method Edit(int id). All of the business logic is within the repository component and the jsonConverter.

If you already have unit test coverage for these two components then you don't need to unit test this, but if you insist on 100% unit test coverage, you should mock both of these components.

Upvotes: 2

Daniel A. White
Daniel A. White

Reputation: 191037

Did you write the JSON converter? If not, then I wouldn't worry about it. If you did, then I would mock it out.

Upvotes: 2

Related Questions