I have a class that looks like this:
public int DoWork(int value)
{
return value + GetDataFromDB();
}
public int GetDataFromDB()
{
return 10;
}
In the real world the second function goes out to the database and gets the value, which is not what I want for unit tests.
Using FakeItEasy my test looks something like this:
public void DoWorkTest()
{
// Arrange
DoWorkClass fake = new DoWorkClass(config);
A.CallTo(() => fake.GetDataFromDB()).Returns(1);
// Act
int result = fake.DoWork(5);
// Assert
Assert.That(result, Is.EqualTo(6));
}
However this throws an error:
System.ArgumentException : Object 'DoWorkClass' of type DoWorkClass is not recognized as a fake object
How do I use FakeItEasy to fake the database call function?
DoWorkClassshould be accepting the data access component in its constructor, which your unit test can mock. The "config" you're passing suggests database configuration, which means the class is responsible for too much , both data access and business logic. What ends up happening is 1) your tests become tautological (it passes because the test was written in a way that it will always pass), and/or 2) your tests have to deal with implementation details (not appropriate for unit tests).DoWorkClassis what you want to test, so there's no point in faking it; you want to test the real thing. What you need to do is extract the external dependencies (e.g. DB access) to separate classes, and fake that.