What is the difference between mocking, stubbing, and faking?
4 minintermediatetestingmockingtest-doubles
Quick Answer
These are types of test doubles. A stub provides canned answers to calls, used to supply indirect inputs. A mock is preconfigured with expectations and verifies that interactions (calls/arguments) happened — it's about behavior verification. A fake is a working but simplified implementation (e.g., an in-memory repository) used in place of a real dependency. Choose based on whether you need to provide data (stub/fake) or assert interactions (mock).
Detailed Answer
These are different types of test doubles used to isolate code during testing:
Stubbing:
- Provides predefined answers to method calls
- Used when you need to control what dependencies return
- Doesn't verify interactions
- Simple, passive replacement
var userRepository = new Mock();
userRepository.Setup(x => x.GetById(1)).Returns(new User { Id = 1, Name = "John" });
Mocking:
- Records and verifies interactions with dependencies
- Used to verify that specific methods were called with expected parameters
- Active verification of behavior
var emailService = new Mock();
// Act
service.SendWelcomeEmail(userId);
// Assert
emailService.Verify(x => x.Send(It.IsAny(), "Welcome!"), Times.Once);
Faking:
- Working implementation with shortcuts (not production-ready)
- More complex than stubs, simpler than real implementations
- Example: in-memory database instead of real SQL database
public class FakeUserRepository : IUserRepository
{
private List _users = new();
public User GetById(int id) => _users.FirstOrDefault(u => u.Id == id);
public void Add(User user) => _users.Add(user);
}
Key Difference: Stubs provide data, mocks verify behavior, fakes are simplified implementations.