How to force moq to call the constructor?

I have a unit test to verify that an object (say Foo) will call a specific method (say Bar) when an event is fired with specific eventArgs. To mock the specified method, I use virtual and stub the classFoo

Mock<Foo> stubbedFoo = new Mock<Foo>(mockEventProvider);

mockEventProvider.Raise( x => x.MyEvent += null, myEventArgs ) //fire the event
stubbedFoo.Verify(foo => foo.Bar()); verify Bar is called as a result

However, the above failed, Bar will not be called, apparently because the Foo object is not an event. However, if I add a line as shown below:

Mock<Foo> stubbedFoo = new Mock<Foo>(mockEventProvider);
var workAround = stubbedFoo.Object //adding this workaround will work
mockEventProvider.Raise( x => x.MyEvent += null, myEventArgs ) //fire the event
stubbedFoo.Verify(foo => foo.Bar()); verify Bar is called as a result

It will work, because calling get.Object seems to force mock to build the object. Is there a more elegant solution than adding this line?

+5
source share
1 answer

, . moq , - castle , .Object. :

public object Object
{
    get { return this.GetObject(); }
}

private object GetObject()
{
    var value = this.OnGetObject();
    this.isInitialized = true;
    return value;
}

protected override object OnGetObject()
{
    if (this.instance == null)
    {
        this.InitializeInstance();
    }

    return this.instance;
}

:

private void InitializeInstance()
{
    PexProtector.Invoke(() =>
    {
        this.instance = proxyFactory.CreateProxy<T>(
            this.Interceptor,
            this.ImplementedInterfaces.ToArray(),
            this.constructorArguments);
    });
}

ProxyFactory

public T CreateProxy<T>(ICallInterceptor interceptor, Type[] interfaces, object[] arguments)
{
    var mockType = typeof(T);

    if (mockType.IsInterface)
    {
        return (T)generator.CreateInterfaceProxyWithoutTarget(mockType, interfaces, new Interceptor(interceptor));
    }

    try
    {
        return (T)generator.CreateClassProxy(mockType, interfaces, new ProxyGenerationOptions(), arguments, new Interceptor(interceptor));
    }
    catch (TypeLoadException e)
    {
        throw new ArgumentException(Resources.InvalidMockClass, e);
    }
    catch (MissingMethodException e)
    {
        throw new ArgumentException(Resources.ConstructorNotFound, e);
    }
}
+1

All Articles