Mocking the System.Diagnostic.Debug class

2 posts, 0 answers
  1. David Parvin
    David Parvin avatar
    4 posts
    Member since:
    May 2010

    Posted 17 Aug 2012 Link to this post

    I want to put a Debug Assert into a function that I am giving to programmers so they make sure to pass the correct information into the routine when they code against it.  The problem is I want my test to be able to see that the assert happens.  The code in the routine will handle the invalid parameter correctly if it is compiled as is and sent to a user and the user will not get the assert because they get the released version.

    What I want to do is have my tests run without the assert screen getting show while when the programmer runs it in the actual code, it gives them the assertion.

    What I have done so far is:

    using System.Diagnostics;
     
            [ClassInitialize()]
            public static void MyClassInitialize(
                TestContext testContext)
            {
                Mock.Initialize(typeof(Debug));
                Mock.Partial(typeof(Debug)).For<bool, string>((i, j) => Debug.Assert(i, j));
            }
     
            public void Test()
            {
                Mock.Arrange(() => Debug.Assert(Arg.AnyBool, Arg.AnyString)).DoNothing();
     
                DoSomeFunctionThatAsserts();
            }

    The Assert screen still comes up.  I am not sure what I am missing in this process.  Can you guys help me out here?  Is this something that is possible or do I just have to remove the assert and throw an exception instead?

    David Parvin
  2. Mihail
    Admin
    Mihail avatar
    75 posts

    Posted 20 Aug 2012 Link to this post

    Hi David,

    Thank you for your question. Your scenario is not common but still a valid one. Because System.Diagnostics.Debug type is declared in System.dll assembly there is no need for using Mock.Partial(...) method. Instead I would recommend using the standard JustMock syntax. Please have a look at the test below.

    [TestMethod]
    public void ShouldAssertMockingDebug()
    {
     bool called = false;

     // arrange
     Mock.Arrange(() => System.Diagnostics.Debug.Assert(Arg.AnyBool, Arg.AnyString)).DoInstead(() => called = true);

     // act
     System.Diagnostics.Debug.Assert(false, "error");

     // assert
     Assert.True(called);
    }


    Please let me know if this works for you.

    All the best,

    Mihail
    the Telerik team

    Explore the entire Telerik portfolio by downloading Telerik DevCraft Ultimate.

  3. DevCraft R3 2016 release webinar banner
Back to Top