1

So I'm pretty new to testing and while it makes a lot of sense to me, some things just don't feel right.

For example: Is it acceptable to use quite a lot of mocks to test a method?

Specifically, I'm testing my Service Layer which has a method to book a date. There are a lot of plausibility checks so it looks a bit like this: (not actual code)

public bool BookDate(Person person, int dateId, MyRoom room...)
{
  var date = this.dateRepo.Get(dateId)
  if (date == null) return false

  if (!this.personService.Get(person.id)) return false;

  if (!this.personService.IsValidPerson(person)) return false;

  ... more validations
}

So the method has to do validations and those, in turn, are dependent on the data provided of course (if they are not interfaces themselves). Testing the different cases means mocking a lot.

Also, I often have to repeat mocking to pass the validations and to get to the actual thing I want to test (for example further down the method, passing a lot of if's)

How can I test this more easily? I could maybe split the method into sub methods but then again, to mock those I would have to expose them in my interface although they're not itself useful to other classes.

EricSchaefer
  • 25,272
  • 21
  • 67
  • 103
lechuckor
  • 11
  • 2
  • Create a fake version of your service backed by an in-memory store. Also make sure you run integration tests as well against the actual service using a dummy db. – Eric Conner May 02 '18 at 13:59
  • 1
    Mock only external resources (file systems, database, web services) or resources which makes tests slow. For other cases use actual implementations. This approach will cover by tests your actual logic, and give you possibility to refactor without changing tests. – Fabio May 03 '18 at 10:31
  • I believe that you need to write unit tests for each cases which you are considered, and you should write unit tests from user input(i.e. UI) to actual response to user. – programtreasures May 03 '18 at 14:33

0 Answers0