Machine.Fakes "WithFakes has not been initialized yet. Are you calling it from a static initializer?" error

StackOverflow https://stackoverflow.com/questions/18632788

  •  27-06-2022
  •  | 
  •  

Question

After updating Machine.Fakes to version 1.7 from 1.0.1 I am getting a "WithFakes has not been initialized yet. Are you calling it from a static initializer?" error/exception.

I am structering my tests like this:

[TestFixture]
public class MailSenderTests : WithSubject<MailSender>
{
    [TestFixture]
    public class TheSendMethod : AssertionHelper
    {
        [Test]
        public void Test_that_exception_is_thrown_if_no_recievers()
        {
            Expect(() => Subject.Send(string.Empty, string.Empty, recievers: null), Throws.InstanceOf<ArgumentException>());
        }
    }
}

I have a class for each method I am testing in the SUT.

Can someone tell me what I am doing wrong?

Was it helpful?

Solution

You are not using Machine.Fakes the way it is intended. It is an extension of Machine.Specifications and does not make sense without it. You are using some other test framework in your code example. This incompatibility has nothing to do with the version - apart from the explicit error message that has been introduced.

To expand on shamp00's answer:

using System;
using Machine.Fakes;
using Machine.Specifications;

namespace SOAnswers
{
    [Subject(typeof(MailSender), "Sending an Email")]
    public class When_no_receivers_are_specified : WithSubject<MailSender>
    {
        static Exception exception;

        Because of = () =>
            exception = Catch.Exception(() => Subject.Send(string.Empty, string.Empty, receivers: null));

        It should_throw_an_exception = () =>
            exception.ShouldBeOfType<ArgumentException>();
    }
}

I think this is very expressive. :-) However, if you don't want to use Machine.Specifications, I suppose you should look for an automocking framework that fits better.

OTHER TIPS

Well I guess a lot has changed since version 1.0.1. With version 1.7.0, your test should look like this

public class Given_a_MailSender : WithSubject<MailSender>
{
    static Exception Exception;

    Because of = () =>
    {
        Exception = Catch.Exception(() => Subject.Send(string.Empty, string.Empty, receivers: null));
    };

    It should_throw_an_exception = () => Exception.ShouldBeOfType<ArgumentException>();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top