Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>You don't need mocking for this.</strong> You use mocking when two classes work together and you want to replace one class with a mock (fake) one so you only have to test the other one. This is not the case in your example.</p> <p><strong>There is however a way you could use mocks, and that fixes your issue with the 2bln instances.</strong> If you separate the ID generation from the <code>Primitive</code> class and use a generator, you can mock the generator. An example:</p> <p>I've changed <code>Primitive</code> to use a provided generator. In this case it's set to a static variable, and there are better ways, but as an example:</p> <pre><code>public abstract class Primitive { internal static IPrimitiveIDGenerator Generator; protected Primitive() { Id = Generator.GetNext(); } internal int Id { get; private set; } } public interface IPrimitiveIDGenerator { int GetNext(); } public class PrimitiveIDGenerator : IPrimitiveIDGenerator { private int? _previousId; public int GetNext() { try { _previousId = checked(++_previousId) ?? 0; return _previousId.Value; } catch (OverflowException ex) { throw new OverflowException("Cannot instantiate more than (int.MaxValue) unique primitives.", ex); } } } </code></pre> <p>Then, your test case becomes:</p> <pre><code>[Fact(DisplayName = "Test Primitive count limit")] public void TestPrimitiveCountLimit() { Assert.Throws(typeof(OverflowException), delegate() { var generator = new PrimitiveIDGenerator(); for (; ; ) { generator.GetNext(); } }); } </code></pre> <p>This will run a lot faster and now you're only testing whether the ID generator works.</p> <p>Now, when you e.g. want to test that creating a new primitive actually asks for the ID, you could try the following:</p> <pre><code>public void Does_primitive_ask_for_an_ID() { var generator = new Mock&lt;IPrimitiveIDGenerator&gt;(); // Set the expectations on the mock so that it checks that // GetNext is called. How depends on what mock framework you're using. Primitive.Generator = generator; new ChildOfPrimitive(); } </code></pre> <p>Now you have separated the different concerns and can test them separately.</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.
 

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