Usage of Moq When(Func) method

前端 未结 2 1876
独厮守ぢ
独厮守ぢ 2021-02-11 22:01

I can\'t find an example of the usage of the When method in Moq

When(Func condition);

What is the purpose/usage of the method? Plea

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-11 22:45

    "When" gives you the option to have different setups for the same mocked object, depending on whatever you have to decide. Let's say you want to test a format provider you have written. If the program (= test) runs in the morning a certain function call should return null; in the afternoon a certain value. Then you can use "When" to write those conditional setups.

    var mockedService = new Mock();
    
    mockedService.When(() => DateTime.Now.Hour < 12).Setup(x => x.GetFormat(typeof(string))).Returns(null);
    mockedService.When(() => DateTime.Now.Hour >= 12).Setup(x => x.GetFormat(typeof(string))).Returns(42);
    

提交回复
热议问题