简体   繁体   中英

Mock a constructor with MOQ

I have a class B with a constructor parameter of Type class A.

I want that class A is mocked when I create a mock for class B.

How can I do this? I tried MockBehavior Loose/Strict but this did not help!

If you are mocking classes you can pass in the constructor arguments when calling new Mock<T> :

So if you have the classes:

public class A {}

public class B
{
    private readonly A a;

    public B(A a) { this.a = a; }
}

The following code creates a mock B with a mock A:

var mockA = new Mock<A>();
var mockB = new Mock<B>(mockA.Object);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM