0

This may be overasked, but I just couldn't grasp what is it for, and when/why I use it. Since I'm learning dart, I'm gonna give my example in dart and I hope I'll get answer in dart too. Also I'm new with unit testing.

Imagine I have 3 class, a Person, a Translator, a Db. Person can do query, Translator translates the query given by Person, so Db can process it.

class Person {
  query(String args, Translator translator) => 
      translator.query(args);
}

class Translator {
  Db db;

  Translator(this.db);

  query(args) => db.query(args); // assuming Translator knows what the db type is
}

class Db {
  String type;

  Db(this.type);

  query(args) => // query with args, return the result;
}

Now I want to test if the Translator is doing good:

void main() {
  var mongoDB = new Db('mongodb'),
      translator = new Translator(mongoDB),
      person = new Person(),
      result = person.query('give me 1 Person named Andy', translator); // get the result

  expect(result['name'], equals('Andy'));
}

From what I have read, mocking is used if I have a case like above, Translator's dependency with Db and a Db io.

Which class should I mock, Translator or Db ?

In what way/how do I mock the class?

What benefit I get from mocking?

1 Answer 1

1

The main purpose of a mocking framework is to simulate the integration to external systems in your code. If you don't mock the dependencies you are writing an integration test, and not a unit test. A big benefit of this is that you don't have dependencies on existing data in the external systems (data in the DB etc). There is also a performance benefit since you don't have to make potentially slow calls to external systems.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.