1

我必须验证是否使用一系列参数调用目标方法中的方法,如下所示。例如,如何验证RepairCar()是先用car参数调用的,而不是car2.

[TestClass]
    public class TestMethodParam
    {
        [TestMethod]
        public void TestMethod1()
        {
            Mock<ICarService> carService = new Mock<ICarService>(MockBehavior.Strict);

            var car = new Car
                {
                    Name = "1"
                };

            var car2 = new Car
            {
                Name = "2"
            };

            var carManager = new CarManager(carService.Object);

            //act
            carManager.Serve();

            //assert: 
            carService.Verify(c => c.RepairCar(It.Is<Car>(actualCar => actualCar.Name == car.Name)), Times.Once());
            carService.Verify(c => c.RepairCar(It.Is<Car>(actualCar => actualCar.Name == car2.Name)), Times.Once());



        }
    }

    public interface ICarService
    {
        void RepairCar(Car car);
    }

    public class Car
    {
        public string Name { get; set; }
    }


    public class CarManager
    {
        private ICarService carService;

        public CarManager(ICarService carService)
        {
            this.carService = carService;
        }
        public void Serve()
        {
            var car = new Car
                {
                    Name = "1"
                };

            carService.RepairCar(car);

            var car2 = new Car
            {
                Name = "2"
            };

            carService.RepairCar(car2);
        }
    }
4

1 回答 1

1

我知道实现这一点的唯一方法是使用回调并使用一些列表来记住调用顺序。

[TestClass]
    public class TestMethodParam
    {
        [TestMethod]
        public void TestMethod1()
        {
            var repairCarCalls = new List<string>();
            Mock<ICarService> carService = new Mock<ICarService>();

            var car = new Car
            {
                Name = "1"
            };

            var car2 = new Car
            {
                Name = "2"
            };

            carService.Setup(c => c.RepairCar(It.IsAny<Car>())).Callback<Car>(c => repairCarCalls.Add(c.Name));

            var carManager = new CarManager(carService.Object);

            //act
            carManager.Serve();

            //assert: 
            var expectedCalls = new[] { car.Name, car2.Name };
            CollectionAssert.AreEqual(expectedCalls, repairCarCalls);
        }
    }
于 2013-05-05T12:21:30.760 回答