c# - Moq simple example required- database connection and file handling -


i quite new unit testing. though can simple unit test, finding difficult understand dependency injection part. have 2 scenarios not create test

  1. database connection
  2. log file handling

though searched internet , not find simple example follow , implement these mocking.

can moq supports concrete class or should need change implementation virtual unit testing. example code or link sample code appreciated

first of all, moq not support mocking concrete classes. abstract classes , interfaces can mocked. however, not hard sounds. let's take log file handling example.

say start following concrete logging class:

public class log {     public void writetolog(string message)     {         ...     } } 

we have classes uses log class logging:

public class loggenerator {     public void foo()     {         ...          var log = new log();         log.writetolog("my log message");     } } 

the problem unit testing foo method have no control on creation of log class. first step apply inversion of control, caller gets decide instances used:

public class loggenerator {     private readonly log log;      public loggenerator(log log)     {         this.log = log;     }      public void foo()     {         ...         this.log.writetolog("my log message");     } } 

now 1 step closer unit testing our unit test can choose log instance logging with. last step make log class mockable, adding interface ilog implemented log , have loggenerator depend on interface:

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");     } } 

now can use moq in our unit test create mock of object implementing ilog:

public void foologscorrectly() {     // arrange     var logmock = new mock<ilog>();     var loggenerator = new loggenerator(logmock.object);      // act     loggenerator.foo();      // assert     logmock.verify(m => m.writetolog("my log message")); } 

Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -