Search code examples
c#.netunit-testingxunit

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. 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?

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);
        
        }
    }
}

Solution

  • 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:

    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.