how to mock/inject a getter into a system under test?

旧巷老猫 提交于 2019-12-24 15:48:56

问题


Mark provides an elegant answer to a related question.

My class has a read only property:

public class myclass
{
    ...
    public virtual string Devicelocation => Message.Message.Items[0].ToString();
    ...
    public someMethod()
    {
        if(Devicelocation=="YourMom")
        {
            //dostuff
        }
        else
        {
            //dootherstuff
        }
    }
}

I would like to execute someMethod() with an assumption for what Devicelocation is equivalent to.

How do I mock or inject a value into Devicelocation?


回答1:


You can set up Devicelocation like this:

var stub = new Mock<myclass>();
stub.SetupGet(x => x.Devicelocation).Returns("YourMom");

stub.Object.Devicelocation will now return "YourMom".

Update:

stub.Object.someMethod();


来源:https://stackoverflow.com/questions/35827217/how-to-mock-inject-a-getter-into-a-system-under-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!