Reputation: 329
I was reading about TDD and wondering is it possible to write any mock object without using extra test library like easyMock or sth like that.
For example I have code:
class Person
{
int age;
int add ( int x) { return this.age + x }
}
How to write mock object to test above code ?
Upvotes: 1
Views: 1162
Reputation: 238491
You don't test a classes like that with a mock of that class. You test interfaces. In fact, your code looks like it could be a mock object to test some other code.
// defined in code that is being tested
class Person {
virtual int add(int) = 0;
}
void foo(const Person& bar) {
// use person somehow
}
To test the above interface, you can create a mock object. This object does not have the requirements that a real implementation might have. For example while a real implementation might require a database connection, the mock object does not.
class Mock: public Person {
int add(int x) {
// do something less complex than real implementation would
return x;
}
}
Mock test;
foo(test);
Using inheritance is not necessary if you want to test say, a template function.
template<class T>
void foo(T bar) {
// Code that uses T.add()
}
To test interface like this, you can define mock object like this
class Mock {
int add(int x) {
// do something less complex than real implementation would
return x;
}
}
Upvotes: 2
Reputation: 15870
Mocking is useful when you have external resources used in your code (e.g. databases, files, etc). To do this, you would implement those interfaces in such a way that it would "fake" the required steps so that the code you are actually testing (your business logic) can be tested without having to worry about a false-negative test due to situations in the external resources.
The code you have posted does not require mocking to test it.
Upvotes: 0