Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>First of all, Moq does <em>not</em> support mocking concrete classes. Only abstract classes and interfaces can be mocked. However, this is not as hard as it sounds. Let's take your log file handling as an example.</p> <p>Say you start with the following concrete logging class:</p> <pre><code>public class Log { public void WriteToLog(string message) { ... } } </code></pre> <p>We have another classes that uses this <code>Log</code> class to do its logging:</p> <pre><code>public class LogGenerator { public void Foo() { ... var log = new Log(); log.WriteToLog("my log message"); } } </code></pre> <p>The problem with unit testing the <code>Foo</code> method is that you have no control over the creation of the <code>Log</code> class. The first step is to apply <strong>inversion of control</strong>, where the caller gets to decide what instances are used:</p> <pre><code>public class LogGenerator { private readonly Log log; public LogGenerator(Log log) { this.log = log; } public void Foo() { ... this.log.WriteToLog("my log message"); } } </code></pre> <p>Now we are one step closer to successfully unit testing as our unit test can choose which <code>Log</code> instance to do the logging with. The last step now is to make the <code>Log</code> class mockable, which we could do by adding an interface <code>ILog</code> that is implemented by <code>Log</code> and have <code>LogGenerator</code> depend on that interface:</p> <pre><code>public interface ILog { void WriteToLog(string message); } public class Log : ILog { public void WriteToLog(string message) { ... } } public class LogGenerator { private readonly ILog log; public LogGenerator(ILog log) { this.log = log; } public void Foo() { ... this.log.WriteToLog("my log message"); } } </code></pre> <p>Now we can use Moq in our unit test to create a mock of an object implementing <code>ILog</code>:</p> <pre><code>public void FooLogsCorrectly() { // Arrange var logMock = new Mock&lt;ILog&gt;(); var logGenerator = new LogGenerator(logMock.Object); // Act logGenerator.Foo(); // Assert logMock.Verify(m =&gt; m.WriteToLog("my log message")); } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload