Object call offset with property of type List

I am learning Moq, and I would like to make fun of the ISecureAsset interface, which has a Contexts property that returns a list of SecurityContexts. I am testing a method on another class that accesses the Contexts property for authorization.

public interface ISecureAsset { List<SecurityContext> Contexts { get; set; } } 

How can I do this with Moq? I also want to be able to set values ​​in the Contexts list.

+4
source share
2 answers

Just configure the property to return a fake list of SecurityContexts.

 var mockAsset = new Mock<ISecureAsset>(); var listOfContexts = new List<SecurityContext>(); //add any fake contexts here mockAsset.Setup(x => x.Contexts).Returns(listOfContexts); 

Moq Quick Start Guide can help you.

+4
source
 var mockSecureAsset = new Mock<ISecureAsset>(); mockSecureAsset.SetupGet(sa => sa.Contexts).Return(new List<SecurityContext>()); 

or

 mockSecureAsset.SetupProperty(sa => sa.Contexts); mockSecureAsset.Object.Contexts = new List<SecurityContext>(); 
+2
source

All Articles