【发布时间】:2019-08-02 07:15:03
【问题描述】:
我正在构建一个简单的机场程序,其中飞机只能在天气晴朗而不是暴风雨的情况下起飞/降落。这取决于天气类(它将天气在晴天和暴风雨之间随机化)。但是,对于我的测试,我想模拟天气,以便可以测试所有情况。
这是我的 Weather.cs:
using System;
namespace ClassNameWeather
{
public class Weather
{
public Weather()
{
}
public string Forecast()
{
Random random = new Random();
var weather = random.Next(1, 11);
if (weather == 1 || weather == 2)
{
return "stormy";
}
else
{
return "sunny";
}
}
}
}
这是我的 Airport.cs:
using System;
using System.Collections.Generic;
using ClassNamePlane;
using ClassNameWeather;
namespace ClassNameAirport
{
public class Airport
{
private string _AirportName { get; set; }
public List<Plane> planes;
private Weather _weather = new Weather();
public Airport(string _airportName, Weather weather)
{
planes = new List<Plane>();
_AirportName = _airportName;
}
public void Land(Plane plane)
{
if (_weather.Forecast() != "stormy")
{
planes.Add(plane);
Console.WriteLine($"{ plane.Name } has landed at {_AirportName}");
}
else
{
throw new Exception("It's too stormy to land");
}
}
public void TakeOff(Plane plane)
{
if (_weather.Forecast() != "stormy")
{
planes.Remove(plane);
Console.WriteLine($"{ plane.Name } has departed from {_AirportName}");
}
else
{
throw new Exception("It's too stormy to take off");
}
}
public int GetPlaneCount()
{
Console.WriteLine($"Number of planes at {_AirportName}: {planes.Count}");
return planes.Count;
}
public void GetPlaneNames()
{
planes.ForEach(plane => Console.WriteLine((plane as Plane).Name));
}
public List<Plane> GetPlaneList()
{
return planes;
}
}
}
这是我尝试在其中使用模拟的测试:
using NUnit.Framework;
using ClassNameAirport;
using ClassNamePlane;
using ClassNameWeather;
using Moq;
namespace AirportTest
{
public class AirportTest
{
Airport airport = new Airport("TestAirport", weather);
Plane plane = new Plane("TestPlane");
[Test]
public void PlaneCanLand()
{
var weather = new Mock<Weather>();
weather.Setup(x => x.Forecast()).Returns("sunny");
airport.Land(plane);
Assert.IsTrue(airport.planes.Contains(plane));
}
public void PlaneCanTakeOff()
{
airport.Land(plane);
airport.TakeOff(plane);
Assert.IsFalse(airport.planes.Contains(plane));
}
}
}
这条线:Airport airport = new Airport("TestAirport", weather); 不工作,说天气这个名字不存在。
谁能帮助我确保我正确使用了起订量?我是 C# 新手,非常感谢任何建议。
谢谢!
更新 我已解决此问题,但现在收到以下错误:
System.NotSupportedException : Unsupported expression: x => x.Forecast()
Non-overridable members (here: Weather.Forecast) may not be used in setup / verification expressions.
请问有人知道怎么解决吗?
【问题讨论】:
-
你已经初始化了 Airport 类里面的 Weather,比如
private Weather _weather = new Weather();weather没有使用构造函数参数,你应该重写你的类,因为模拟不起作用 -
谢谢@PavelAnikhouski 你介意解释一下重写课程是什么意思吗?
标签: c# unit-testing mocking nunit moq