Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid Database Dependency For Unit Testing Without Mocking

I've got many objects with methods that require database access. We're looking to get into unit testing but are keen to avoid the use of mock objects if possible. I'm wondering if there is a way to refactor the Validate method shown below so that it wouldn't need db access. In the actual application there is usually a fair bit more going on but I think this simplified example should be enough.

We'll learn to use mock objects if we need to but it just seems like a lot of overhead, so I'm looking for alternatives.

    public class Person
    {
        public string Name;

        public string Validate()
        {
            if (PersonDA.NameExists(Name))
            {
                return "Name Already Used";
            }

        }
    }
like image 319
tjjjohnson Avatar asked Jun 07 '09 21:06

tjjjohnson


People also ask

Should all dependencies be mocked in a unit test?

Mocking is a very popular approach for handling dependencies while unit testing, but it comes at a cost. It is important to recognize these costs, so we can choose (carefully) when the benefits outweigh that cost and when they don't.

Should I mock database for unit testing?

The use of mocks in unit testing is a controversial topic (maybe less so now than several years ago).

Why mocking is necessary in unit testing?

Mocking is used in unit tests to replace the return value of a class method or function. This may seem counterintuitive since unit tests are supposed to test the class method or function, but we are replacing all those processing and setting a predefined output.

Is mocking bad in unit testing?

Automated testing during software development involves many different techniques, one that shouldn't be used is mocking. Mocks are a distraction at best and provide false confidence at worst.


1 Answers

Personally I'd just go the mock object route. It's much more flexible and it sounds like you're wanting to go the route of putting test code in your actual object?

Regarless, extract the validation code into a PersonValidator object with a method for boolean isValid(Person). Then in the test code use a mock validator which just returns true or false based on the test case.

like image 79
NeilInglis Avatar answered Oct 03 '22 16:10

NeilInglis