gpt4 book ai didi

c# - 单元测试组织

转载 作者:行者123 更新时间:2023-11-30 09:54:12 25 4
gpt4 key购买 nike

我目前正在使用以下代码来初始化类中的一些单元测试:

[TestClass]
public class BoardTests_SquarePieceFalling
{
private Engine engine;
private BackgroundBoard backgroundBoard;
private PieceBoard pieceBoard;

private IFallingPieceFactory GetFallingPieceFactory(FallingPiece fallingPieceToReturn)
{
var factory = new Mock<IFallingPieceFactory>();
factory.Setup(f => f.Generate()).Returns(fallingPieceToReturn);
return factory.Object;
}

private void TestInitializer(Color pieceColor, Size boardSize) {
backgroundBoard = new BackgroundBoard(boardSize);
pieceBoard = new PieceBoard(boardSize);

var fallingPiece = new FallingPiece(new SquarePiece(), pieceColor, boardSize.Width);
var fallingPieceFactory = GetFallingPieceFactory(fallingPiece);
var currentFallingPiece = new CurrentFallingPiece(fallingPieceFactory);
var fallingPieceMovementEvaluator = new FallingPieceMovementEvaluator(backgroundBoard, currentFallingPiece, boardSize);

engine = new Engine(backgroundBoard, pieceBoard, currentFallingPiece, fallingPieceMovementEvaluator);
}

...Unit-Tests are below

[TestMethod]
public void When_Square_Hits_The_Ground_Another_One_Starts_Falling_From_The_Top()
{
TestInitializer(Color.Red, new Size(2, 7));

engine.Tick(10);

..Asserts..
}

...
}

现在,我想我目前在这个类上有太多的测试方法。我也相信它们涵盖了很多领域,所以我想将它们分成较小的测试类。

我的问题是:

  1. 目前,这是初始化测试的最佳方式吗?我知道我可以使用 [TestInitialize] 注释,但这不允许我将参数传递给我要使用的字段的初始化,是吗?

  2. 我打算将当前测试类拆分为 2-3 个较小的测试类。我目前的想法是在初始化逻辑所在的地方创建一个基本测试类,然后让所有这些新类继承它。我看到的唯一区别是必须将 EngineBackgroundBoardPieceBoard 作为 protected 字段。这是个好主意吗?

  3. 您通常如何处理非常相似但通常总是至少有 1 个不同设置字段的单元测试?我的意思是,在我的很多单元测试中,我都有相同的 EngineBackgroundBoardPieceBoardFallingPieceCurrentFallingPieceFallingPieceFactory 等等,但通常其中一两个对于每个测试都是不同的。我通过在每次测试中使用我需要的参数定义 TestInitializer() 方法来规避这个问题,但我想知道是否有任何其他方法可以做到这一点。

谢谢

最佳答案

一般来说,每个被测试的类有一个测试类(文件)是最清楚的。

所以你应该有一个EngineTestBackgroundBoardTest

关于c# - 单元测试组织,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3470853/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com