3

I have a class PhotoOrganiser and am trying to unit test its method SortAll. This method calls another method in the class, MovePhoto.

What is the correct way to go about this? Using Moq, I have mocked out the other classes SortAll references, but as far as I can see there is no way to mock just one method on an object without mocking the object itself. Is the cleanest way to do this simply to create a new subclass which overrides MovePhoto?

5
  • github.com/Moq/moq4/wiki/Quickstart ctrl-f for "partial" Commented Jan 11, 2015 at 9:50
  • Zerkms is right. The thing you're looking for is partial mock. Moq supports it. Commented Jan 11, 2015 at 10:01
  • Thanks guys, I missed that. Doing that then, I would have to make the methods to override virtual? Is it considered good practise to do so purely for the purpose of testing (as opposed to for use within the program itself)? Commented Jan 11, 2015 at 10:04
  • @tsvallender I use partial mocks when necessary. Not sure if it's considered good or bad by community though :-) Commented Jan 11, 2015 at 10:05
  • IMO: don't. You're testing the class with its public API like any consumer would, so test the logic accordingly. Do not test "method by method", but by calls/behaviors. Give a shot to TDD, that's exactly what you end up doing. Commented Jan 11, 2015 at 11:17

1 Answer 1

1

You shouldn't need to mock MovePhoto. Your SortAll method sounds like it should have easy to assert, observable result (photos being sorted).

I suggest giving your design a second look. Perhaps PhotoOrganizer class is too complex? Maybe moving photo is large enough piece of work to deserve its own class? Consider what happens when you inline MovePhoto usages within SortAll method. I realize PhotoOrganizer might seem like a good name considering application purpose but in OOP organizer might scream SRP violation. Problems with design are usually very quickly highlighted by hard to write unit tests.

All things considered you can solve it with partial mock as mentioned by others (and yes, it requires method to be virtual). But this is treating symptoms instead of fighting causes.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.