简体   繁体   中英

NSubstitute Returns method and arrays

so I want to test roll results of dice set, but i can't pass an array as arg in Returns method like this:

    [TestCase(new[]{2, 2, 3, 1, 5}, Category.Yahtzee, 0)]
    public void AddPoints_ForGivenCategory_PointsAreStored(
        int[] rollResults, Category selectedCategory, int expectedScore)
    {
        _randomizer.GetRandomNumber(MIN_VALUE, MAX_VALUE).Returns(rollResults); //<-rollResults not allowed
        IDice[] dice = MakeNewDiceSet();

        _game.NewGame("A");
        _game.RollDice(dice);
        _game.AddPoints(selectedCategory);
        var result = _game.GameStatus().First()[selectedCategory];

        Assert.AreEqual(expectedScore, result);
    }

any tips or workarounds for this problem? Or am I forced to do this:

    [TestCase(2, 2, 3, 1, 5, Category.Yahtzee, 0)]
    public void AddPoints_ForGivenCategory_PointsAreStored(
        int die1, int die2, int die3, int die4, int die5, Category selectedCategory, int expectedScore)
    {
        _randomizer.GetRandomNumber(MIN_VALUE, MAX_VALUE).Returns(die1, die2, die3, die4, die5);
        IDice[] dice = MakeNewDiceSet();
        / ...
    }

Using NSubstitute v3.1.0.0

NSubstitute does not have Returns<T>(T[] values) (or similar). Instead it has Returns<T>(T initialValue, params T[] otherValues) to indicate we should always specify at least one value to return. The aim at the time was to avoid the potentially confusing case of stubbing a call with "no values" in the case of an empty collection. (Is it a no-op? Or does it clear the call?)

There are a few ways to get the behaviour you want. One way is to split the values into "first" and "rest":

random.GetRandomNumber(1, 10)
      .Returns(rollResults.First(), rollResults.Skip(1).ToArray());

Another approach is to use a Queue and stub GetRandomNumber() to consume this:

var rolls = new Queue<int>(rollResults);           
random.GetRandomNumber(1, 10).Returns(_ => rolls.Dequeue());

If this is something you need frequently it might be worth creating your own Returns extension that explicitly defines how the empty case should be handled.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM