What is mocking?
๐ก Concept: Mocking in Unit Testing
Mocking is a technique to create fake objects that simulate behavior of real dependencies for unit testing.
๐ Quick Intro
Mocks help isolate the unit under test by providing controlled behavior and verifying interactions.
๐ง Analogy
Like using stunt doubles in movies to test scenes without risking the main actor.
๐ง Technical Explanation
- Mocks implement interfaces or abstract classes.
- Provide predefined responses for method calls.
- Can verify if methods were called or not.
- Common mocking frameworks: Moq, NSubstitute, FakeItEasy.
- Enhances test reliability and speed.
๐ฏ Use Cases
- โ Simulating database or web service calls.
- โ Testing error conditions.
- โ Verifying interactions between components.
- โ Isolating units from external dependencies.
๐ป Code Example
// Using Moq for mocking
var mockRepo = new Mock();
mockRepo.Setup(repo => repo.GetUser(It.IsAny<int>())).Returns(new User { Id = 1, Name = "Test" });
var service = new UserService(mockRepo.Object);
var user = service.GetUser(1);
mockRepo.Verify(repo => repo.GetUser(1), Times.Once);

โ Interview Q&A
Q1: What is mocking?
A: Creating fake objects for unit tests.
Q2: Why use mocking?
A: To isolate the unit under test.
Q3: Name some mocking frameworks.
A: Moq, NSubstitute, FakeItEasy.
Q4: Can mocks verify method calls?
A: Yes.
Q5: What is the difference between mocks and stubs?
A: Mocks verify behavior; stubs provide data.
Q6: Can you mock concrete classes?
A: Sometimes, depending on framework.
Q7: Is mocking only for unit testing?
A: Primarily, yes.
Q8: What is a test double?
A: General term for fake test objects.
Q9: Does mocking slow tests?
A: Usually no, it speeds them up.
Q10: Can mocking detect unwanted calls?
A: Yes, through verification.
๐ MCQs
Q1. What is mocking?
- Creating fake objects
- Calling real methods
- Using database
- Integration testing
Q2. Why use mocking?
- To slow tests
- To isolate the unit
- To mock UI
- For production
Q3. Name a mocking framework.
- NUnit
- Moq
- XUnit
- Selenium
Q4. Can mocks verify calls?
- No
- Yes
- Sometimes
- Never
Q5. Mocks vs stubs?
- Mocks provide data
- Mocks verify behavior
- Stubs verify behavior
- No difference
Q6. Can you mock concrete classes?
- Always
- Sometimes
- Never
- Rarely
Q7. Is mocking only for unit tests?
- No
- Yes
- Sometimes
- Rarely
Q8. What is a test double?
- Real object
- Fake test object
- Database
- UI
Q9. Does mocking slow tests?
- Yes
- No
- Sometimes
- Rarely
Q10. Can mocking detect unwanted calls?
- No
- Yes
- Maybe
- Never
๐ก Bonus Insight
Mocking improves test isolation and reliability by simulating dependencies in unit tests.
๐ PDF Download
Need a handy summary for your notes? Download this topic as a PDF!