如何在XUnit中编写端到端测试

问题描述

我是测试新手并使用XUnit为非常大和复杂的项目编写测试的新手。我不想编写单元测试,而只想编写一个测试(端到端测试)。 我的项目基本上需要一个文件(包含一些项目,比如10个),进行一些处理,然后根据其类型将这些项目推送到不同的列表中。现在,在此之后,将执行一些操作,如果它们运行良好,则最后将从这些列表中删除项目。 我只想写一个测试来检查初始文件中的项目数和删除的项目数是否应该相同(检查所有操作是否都正常,因为删除是最后一步)。一次测试该怎么做?

解决方法

欢迎使用StackOverflow!

您可以像设置xunit单元测试一样设置测试:

[Fact]
public void Given_When_Then() // describe your test
{
  // Arrange - set up the conditions for your test,perhaps set the contents of the file
  var expectedResults = ...;
  System.IO.File.WriteAllText(@"C:\myTestFile.txt","line 1\nline 2\nline 3\nline 4\nline 5\nline 6\nline 7\nline 8\nline 9\nline 10");
  var classUnderTest = new ClassUnderTest();

  // Act - perform your action that will impact the data
  var results = classUnderTest.DoProcessing();

  // Assert - prove that your data is in the correct state
  Assert.Equal(results,expectedResults);
  Assert.Equal(System.IO.File.ReadAllLines(@"C:\myTestFile.txt"),expectedResults);  // or perhaps assert on the files
}

如果您要创建一个使用一系列值来断言不同方案工作的测试,我个人建议检查Xunit的Theory。您还可以签出FluentAssertions以获得一堆直观易读的断言,以使您的测试更强大。

测试愉快!