Bohn
Bohn

Reputation: 26919

Do we lie to ourselves when creating a mock for a unit test

I have just started learning all about unit testing since yesterday and today was reading about Mocks and NSub in particular. The problem I have is that I don't get the philosophy and way of thinking behind it. So for example reading my book came to this:

[Test]
public void Returns_ByDefault_WorksForHardCodedArgument()
{
IFileNameRules fakeRules = Substitute.For<IFileNameRules>();

fakeRules.IsValidLogFileName(Arg.Any<String>())
.Returns(true);

Assert.IsTrue(fakeRules.IsValidLogFileName("anything.txt"));

}

OK so first we make a fake object to represent the interface of the actual class that we have a actual method in it that does some actual work. Then we call that method but we also tell it to return true. Then we assert it to see if it is returning true ? Well we just told it one line before that return true! now we test it is returning true! they we say ok good passed? I don't get it! To me feel like this: Teacher tell the kid in order to pass the exam answer yes to this question if asked, then goes and asks that question and kid says yes and exam is passed?

Upvotes: 1

Views: 119

Answers (2)

David Tchepak
David Tchepak

Reputation: 10484

As per the comments on this question, this test is likely demonstrating how the mocking library works. For our test code we are extremely unlikely (partial mocks being a potential exception) to mock out the class we want to test. Instead we may want to mock out some things the code uses, in order to get more deterministic tests, or faster tests, or tests that simulate rare events, etc.

To your direct question, yes I guess we are sort lying to ourselves when we mock out dependencies for a test. We are saying "let's pretend that our dependency does X, then check our code does Y". Now it is possible the dependency never actually does "X". To me, the aim of mocking is to start off with this fiction, then test our dependency and make sure it actually does do "X", to the point where the fiction ends up matching reality.

Upvotes: 2

AndrewGetsome
AndrewGetsome

Reputation: 26

The purpose of testing is to check every single way a method could possibly behave. If you tell the method a true statement and it returns false. Obviously something is wrong with the method you wrote. Sometimes the most complex issues can be solved by finding simple mistakes in your code. (In this case checking to see if the method will actually return true when asked to return true.) IF it fails to do so. You done messed up.

Upvotes: 1

Related Questions