如何使用[SetUp]方法安排单元测试。参数怎么样?

时间:2015-04-22 02:28:57

标签: c# unit-testing

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
}

===&GT;编写单元测试来测试上述方法是否可以;并使用仅包含2个参数的方法创建CoffeeMaker类和Coffee类对象的新对象?

1 个答案:

答案 0 :(得分:1)

你问的是什么并不是很清楚,但我认为你是在考虑如何测试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));
    }
}