[英]Running unit tests independently (.net core )
Does any one know what type of attribute can we use to run all of the unit tests independently?有谁知道我们可以使用什么类型的属性来独立运行所有单元测试? for example in following we used [Fact] attribute but it does not make tests run independently.
例如在下面我们使用了 [Fact] 属性,但它不会使测试独立运行。 Is there any other type attribute that we can use to initialize data at beginning of each test and make tests run independently from each other?
是否还有其他类型属性可用于在每个测试开始时初始化数据并使测试彼此独立运行? How can I run unit tests independently in visual studio code?
如何在 Visual Studio 代码中独立运行单元测试?
namespace Tests
{
public class TestCategory
{
//Test Get() Method
[Fact]
public void Get_WhenCalled_ReturnsAllCategories()
{
//Arrange
//create _options
var _Options = new DbContextOptionsBuilder<MyContext>()
.UseInMemoryDatabase("Data Source=MyCart.db").Options;
var Context = new MyContext(_Options);
Context.CategoryTestData();//We make sure that dummy data has been added
var Controller = new CategoryController(Context);//pass context inside controller
//Act
var Results = Controller.Get();//call Get() function inside Category controller
//Assert
Assert.NotNull(Results);
}
//Test GetById() Method
//When valid Id is passed
[Fact]
public void GetById_ExistingIntIdPassed_ReturnsOkResult()
{
//Arrange
var _Options = new DbContextOptionsBuilder<MyContext>()
.UseInMemoryDatabase("Data Source=MyCart.db").Options;
var Context = new MyContext(_Options);//pass _Options into context
var Controller = new CategoryController(Context);//pass Context inside controller
//Act
var OkResult = Controller.GetById(1);//1 is valid Id
//Assert
Assert.IsType<OkObjectResult>(OkResult.Result);
}
}
}
If you add a constructor to your class you can set up "initialisation" data etc..如果向类添加构造函数,则可以设置“初始化”数据等。
There is no [Attribute] , if you know other test frameworks, you can have a look at a comparison list to see how the [Attributes] compares to xUnit.没有[Attribute] ,如果您了解其他测试框架,您可以查看一个比较列表,了解[Attributes]与 xUnit 的比较情况。
When you look at * Note 3 on that page you will see it describes the use of an IClassFixture<T>
interface that can be used to share context between tests当您查看该页面上的 * Note 3时,您将看到它描述了
IClassFixture<T>
接口的使用,该接口可用于在测试之间共享上下文
For parallel testing you can configure it in the configuration of xUnit.对于并行测试,您可以在 xUnit 的配置中对其进行配置。
I finally found the answer here: How to isolate EF InMemory database per XUnit test Actually we want that our context not to be shared between the tests hence we have to make a new context at the beginning of each test like this:我终于在这里找到了答案: 如何在每个 XUnit 测试中隔离 EF InMemory 数据库实际上我们希望我们的上下文不在测试之间共享,因此我们必须在每个测试开始时创建一个新的上下文,如下所示:
using (var Context = new myContext(CreateNewContextOptions()))
{
//here we implement Arrange, Act, and Assert parts
}
CreateNewContextOptions() is actually a function that helps us to create a new context. CreateNewContextOptions() 实际上是一个帮助我们创建新上下文的函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.