public class CoffeeStrengthEstimator
{
/// <summary>
/// Estimates the strength of the coffee (how many beans to use) depending on the button pressed
/// </summary>
/// <param name="buttonPressed"> The numeral position of the button pressed</param>
/// <returns>An enum value indicating the estimated coffee strength</returns>
public CoffeeStrength EstimateCoffeeStrength(int buttonPressed)
{
if (buttonPressed == 1)
{
return CoffeeStrength.Light;
}
else if (buttonPressed == 2)
{
return CoffeeStrength.Medium;
}
else if (buttonPressed == 3)
{
return CoffeeStrength.Strong;
}
else
{
throw new ArgumentException ("Invalid Button press, please try again");
}
}
}
public enum CoffeeStrength
{
Light,
Medium,
Strong
}
Run Code Online (Sandbox Code Playgroud)
===> 写一个单元测试来测试上面的方法是否可以;并使用仅需要 2 个参数的方法创建 CoffeeMaker 类的新对象和 Coffee 类的对象?
目前还不清楚您在问什么,但我假设您是在问如何进行测试CoffeeStrengthEstimator(使用 NUnit,基于Setup标题)。
方法SetUp在测试类中的每个测试方法之前运行,因此用于设置每个方法所需的公共代码 - 这可以为被测系统所需的任何依赖项提供存根/假货/模拟,以及可能实例化一个实例被测系统的。
测试方法可以参数化以接收不同的参数。
将它们放在一起,测试类CoffeeStrengthEstimator可能如下所示
[TestFixture]
public class CoffeeStrengthEstimatorTests
{
private CoffeeStrengthEstimator _estimator;
[SetUp]
public void SetUp()
{
// common Arrange
_estimator = new CoffeeStrengthEstimator();
}
[Test]
[TestCase(1, CoffeeStrength.Light)]
[TestCase(2, CoffeeStrength.Medium)]
[TestCase(3, CoffeeStrength.Strong)]
public void EstimateCoffeeStrength_Returns_Expected_CoffeeStrength_For_Button_Pressed_1_2_or_3(int buttonPressed,
CoffeeStrength expectedCoffeeStrength)
{
// Act
var coffeeStrength = _estimator.EstimateCoffeeStrength(buttonPressed);
// Assert
Assert.AreEqual(expectedCoffeeStrength, coffeeStrength);
}
[Test]
[TestCase(-1)]
[TestCase(0)]
[TestCase(4)]
public void EstimateCoffeeStrength_Throws_ArgumentException_When_Button_Pressed_Not_1_2_or_3(int buttonPressed)
{
// Act and Assert
Assert.Throws<ArgumentException>(() => _estimator.EstimateCoffeeStrength(buttonPressed));
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15685 次 |
| 最近记录: |