Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>A good way to allow you to write stubs is to use <strong>dependency injection</strong>. <code>FirstDeep</code> depends on <code>SecondDeep</code> and in your test you want to replace <code>SecondDeep</code> with a stub.</p> <p>First change your existing code by extracting an interface for <code>SecondDeep</code> and then inject that into <code>FirstDeep</code> in the constructor:</p> <pre><code>interface ISecondDeep { Boolean SomethingToDo(String str); } class SecondDeep : ISecondDeep { ... } class FirstDeep { readonly ISecondDeep secondDeep; public FirstDeep(ISecondDeep secondDeep) { this.secondDeep = secondDeep; } public String AddA(String str) { var flag = this.secondDeep.SomethingToDo(str); ... } } </code></pre> <p>Note that <code>FirstDeep</code> no longer creates a <code>SecondDeep</code> instance. Instead an instance is injected in the constructor.</p> <p>In your test you can create a stub for <code>ISecondDeep</code> where <code>SomethingToDo</code> always returns true:</p> <pre><code>class SecondDeepStub : ISecondDeep { public Boolean SomethingToDo(String str) { return true; } } </code></pre> <p>In the test you use the stub:</p> <pre><code>var firstDeep = new FirstDeep(new SecondDeepStub()); </code></pre> <p>In production code you use the "real" <code>SecondDeep</code>:</p> <pre><code>var firstDeep = new FirstDeep(new SecondDeep()); </code></pre> <p>Using a dependency injection container and a stubbing framework can make a lot of this easier to do.</p> <p>If you don't want to rewrite your code you can use a framework for intercepting calls like <a href="http://research.microsoft.com/en-us/projects/moles/">Microsoft Moles</a>. In the next version of Visual Studio a similar technology will be available in the <a href="http://msdn.microsoft.com/en-us/library/hh549175%28v=vs.110%29.aspx">Fakes Framework</a>.</p>
    singulars
    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.
    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