how to run multiple unit tests using same data












0















I'm trying to implement unit tests for a rest api I created. When I run the tests separately, they pass. But when I try to run all of them in 1 go, only 1 passes.



I know it has something to do with way I try to use the same data in evry test. I found a solution by using a new database(name) for every test. But I was wondering if this is the correct way to go about it? Since I think there has to be a cleaner way. I looked into the IDisposable method, but I coudn't get it to work.



This is how I put data in the db to test against:



public class GameTestShould
{
private static GameService gameService;

private readonly DbContextOptions<GameContext> options;
public readonly Game testGame;
public readonly User testUser;
public Location testLocation;


public GameTestShould()
{
//Arrange For the all tests
options = new DbContextOptionsBuilder<GameContext>().UseInMemoryDatabase(databaseName: "GameTestDB").Options;
//arrange
using (var globalContext = new GameContext(options))
{
gameService = new GameService(globalContext);

var testUser = new User()
{
Username = "tempUser",
Password = "123456"
};
globalContext.Users.Add(testUser);
var location2 = new Location()
{
LocName = "Standbeeld Stadhuis",
LocLat = 51.220884,
LocLong = 4.398995,
LocDescription = "Standbeeld Vrijheid blijheid nabij stadhuis."
};
var location3 = new Location()
{
LocName = "Het Steen",
LocLat = 51.222773,
LocLong = 4.397367,
LocDescription = "Het Steen"
};
var location4 = new Location()
{
LocName = "Pieter Paul Rubens",
LocLat = 51.219326,
LocLong = 4.401576,
LocDescription = "Groenplaats, standbeeld Pieter Paul Rubens."
};
var location5 = new Location()
{
LocName = "Politiekantoor",
LocLat = 51.230754,
LocLong = 4.4174065,
LocDescription = "Politiekantoor"
};
globalContext.Add(location2);
globalContext.Add(location3);
globalContext.Add(location4);
globalContext.Add(location5);

var suspect0 = new Suspect()
{
// SuspectId = 1,
SusName = "Miss Scarlett",
SusWeapon = "Rope",
SusDescription = "Ms. Vivienne Sakura Scarlet",
SusImgUrl = "https://i.pinimg.com/originals/95/ce/3d/95ce3da06af8b1c09a4b2d4fa603b7a0.jpg",
};
var suspect1 = new Suspect()
{
SusName = "Mr. Green",
SusWeapon = "Wooden cross",
SusDescription = "Rev. Jonathan Green.",
SusImgUrl = "https://pbs.twimg.com/profile_images/447953368271814657/Inf33QvJ.jpeg",
};
var suspect2 = new Suspect()
{
SusName = "Colonel Mustard",
SusWeapon = "Gun",
SusDescription = "Col. Michael Mustard",
SusImgUrl = "https://static.independent.co.uk/s3fs-public/thumbnails/image/2016/07/04/08/unspecified-3.jpg?width=1368&height=912&fit=bounds&format=pjpg&auto=webp&quality=70",
};

var suspect3 = new Suspect()
{
SusName = "Dr.Orchid",
SusWeapon = "Syringe",
SusDescription = "A Doctor, Elegant ",
SusImgUrl = "https://static.independent.co.uk/s3fs-public/thumbnails/image/2016/07/04/08/unspecified-4.jpg?width=1368&height=912&fit=bounds&format=pjpg&auto=webp&quality=70",
};
globalContext.Suspects.Add(suspect0);
globalContext.Suspects.Add(suspect1);
globalContext.Suspects.Add(suspect2);
globalContext.Suspects.Add(suspect3);

var clue0 = new Clue()
{
ClueName = "RansomPuzzle"
};
var clue1 = new Clue()
{
ClueName = "ARKnife"
};
var clue2 = new Clue()
{
ClueName = "ARRope"
};
globalContext.Clues.Add(clue0);
globalContext.Clues.Add(clue1);
globalContext.Clues.Add(clue2);
globalContext.SaveChanges();
}
}


This is first test



   [Fact]
public void Throw_AppExceptionTooManyItems_Over8ItemsAdded()
{
var options = new DbContextOptionsBuilder<GameContext>().UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options;

using (var globalContext = new GameContext(options))
{
gameService = new GameService(globalContext);
//act and assert
Exception ex = Assert.Throws<AppException>(() => gameService.CreateGame(1, 2));
Assert.Contains("between", ex.Message);
}
}


2nd test. Here (I think) I make another db, but doesn't this just leave the data from previous test laying around? So if I were to make alot of tests, woudn't it slow down the test process?



   [Fact]
public void Throw_AppExceptionWrongUser()
{
var options = new DbContextOptionsBuilder<GameContext>().UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options;

using (var globalContext = new GameContext(options))
{
gameService = new GameService(globalContext);
//act and assert
Exception ex = Assert.Throws<AppException>(() => gameService.CreateGame(2, 3));
Assert.Equal("User does not exist.", ex.Message);
}
}
}


}



Are there better ways to go about this?










share|improve this question



























    0















    I'm trying to implement unit tests for a rest api I created. When I run the tests separately, they pass. But when I try to run all of them in 1 go, only 1 passes.



    I know it has something to do with way I try to use the same data in evry test. I found a solution by using a new database(name) for every test. But I was wondering if this is the correct way to go about it? Since I think there has to be a cleaner way. I looked into the IDisposable method, but I coudn't get it to work.



    This is how I put data in the db to test against:



    public class GameTestShould
    {
    private static GameService gameService;

    private readonly DbContextOptions<GameContext> options;
    public readonly Game testGame;
    public readonly User testUser;
    public Location testLocation;


    public GameTestShould()
    {
    //Arrange For the all tests
    options = new DbContextOptionsBuilder<GameContext>().UseInMemoryDatabase(databaseName: "GameTestDB").Options;
    //arrange
    using (var globalContext = new GameContext(options))
    {
    gameService = new GameService(globalContext);

    var testUser = new User()
    {
    Username = "tempUser",
    Password = "123456"
    };
    globalContext.Users.Add(testUser);
    var location2 = new Location()
    {
    LocName = "Standbeeld Stadhuis",
    LocLat = 51.220884,
    LocLong = 4.398995,
    LocDescription = "Standbeeld Vrijheid blijheid nabij stadhuis."
    };
    var location3 = new Location()
    {
    LocName = "Het Steen",
    LocLat = 51.222773,
    LocLong = 4.397367,
    LocDescription = "Het Steen"
    };
    var location4 = new Location()
    {
    LocName = "Pieter Paul Rubens",
    LocLat = 51.219326,
    LocLong = 4.401576,
    LocDescription = "Groenplaats, standbeeld Pieter Paul Rubens."
    };
    var location5 = new Location()
    {
    LocName = "Politiekantoor",
    LocLat = 51.230754,
    LocLong = 4.4174065,
    LocDescription = "Politiekantoor"
    };
    globalContext.Add(location2);
    globalContext.Add(location3);
    globalContext.Add(location4);
    globalContext.Add(location5);

    var suspect0 = new Suspect()
    {
    // SuspectId = 1,
    SusName = "Miss Scarlett",
    SusWeapon = "Rope",
    SusDescription = "Ms. Vivienne Sakura Scarlet",
    SusImgUrl = "https://i.pinimg.com/originals/95/ce/3d/95ce3da06af8b1c09a4b2d4fa603b7a0.jpg",
    };
    var suspect1 = new Suspect()
    {
    SusName = "Mr. Green",
    SusWeapon = "Wooden cross",
    SusDescription = "Rev. Jonathan Green.",
    SusImgUrl = "https://pbs.twimg.com/profile_images/447953368271814657/Inf33QvJ.jpeg",
    };
    var suspect2 = new Suspect()
    {
    SusName = "Colonel Mustard",
    SusWeapon = "Gun",
    SusDescription = "Col. Michael Mustard",
    SusImgUrl = "https://static.independent.co.uk/s3fs-public/thumbnails/image/2016/07/04/08/unspecified-3.jpg?width=1368&height=912&fit=bounds&format=pjpg&auto=webp&quality=70",
    };

    var suspect3 = new Suspect()
    {
    SusName = "Dr.Orchid",
    SusWeapon = "Syringe",
    SusDescription = "A Doctor, Elegant ",
    SusImgUrl = "https://static.independent.co.uk/s3fs-public/thumbnails/image/2016/07/04/08/unspecified-4.jpg?width=1368&height=912&fit=bounds&format=pjpg&auto=webp&quality=70",
    };
    globalContext.Suspects.Add(suspect0);
    globalContext.Suspects.Add(suspect1);
    globalContext.Suspects.Add(suspect2);
    globalContext.Suspects.Add(suspect3);

    var clue0 = new Clue()
    {
    ClueName = "RansomPuzzle"
    };
    var clue1 = new Clue()
    {
    ClueName = "ARKnife"
    };
    var clue2 = new Clue()
    {
    ClueName = "ARRope"
    };
    globalContext.Clues.Add(clue0);
    globalContext.Clues.Add(clue1);
    globalContext.Clues.Add(clue2);
    globalContext.SaveChanges();
    }
    }


    This is first test



       [Fact]
    public void Throw_AppExceptionTooManyItems_Over8ItemsAdded()
    {
    var options = new DbContextOptionsBuilder<GameContext>().UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options;

    using (var globalContext = new GameContext(options))
    {
    gameService = new GameService(globalContext);
    //act and assert
    Exception ex = Assert.Throws<AppException>(() => gameService.CreateGame(1, 2));
    Assert.Contains("between", ex.Message);
    }
    }


    2nd test. Here (I think) I make another db, but doesn't this just leave the data from previous test laying around? So if I were to make alot of tests, woudn't it slow down the test process?



       [Fact]
    public void Throw_AppExceptionWrongUser()
    {
    var options = new DbContextOptionsBuilder<GameContext>().UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options;

    using (var globalContext = new GameContext(options))
    {
    gameService = new GameService(globalContext);
    //act and assert
    Exception ex = Assert.Throws<AppException>(() => gameService.CreateGame(2, 3));
    Assert.Equal("User does not exist.", ex.Message);
    }
    }
    }


    }



    Are there better ways to go about this?










    share|improve this question

























      0












      0








      0








      I'm trying to implement unit tests for a rest api I created. When I run the tests separately, they pass. But when I try to run all of them in 1 go, only 1 passes.



      I know it has something to do with way I try to use the same data in evry test. I found a solution by using a new database(name) for every test. But I was wondering if this is the correct way to go about it? Since I think there has to be a cleaner way. I looked into the IDisposable method, but I coudn't get it to work.



      This is how I put data in the db to test against:



      public class GameTestShould
      {
      private static GameService gameService;

      private readonly DbContextOptions<GameContext> options;
      public readonly Game testGame;
      public readonly User testUser;
      public Location testLocation;


      public GameTestShould()
      {
      //Arrange For the all tests
      options = new DbContextOptionsBuilder<GameContext>().UseInMemoryDatabase(databaseName: "GameTestDB").Options;
      //arrange
      using (var globalContext = new GameContext(options))
      {
      gameService = new GameService(globalContext);

      var testUser = new User()
      {
      Username = "tempUser",
      Password = "123456"
      };
      globalContext.Users.Add(testUser);
      var location2 = new Location()
      {
      LocName = "Standbeeld Stadhuis",
      LocLat = 51.220884,
      LocLong = 4.398995,
      LocDescription = "Standbeeld Vrijheid blijheid nabij stadhuis."
      };
      var location3 = new Location()
      {
      LocName = "Het Steen",
      LocLat = 51.222773,
      LocLong = 4.397367,
      LocDescription = "Het Steen"
      };
      var location4 = new Location()
      {
      LocName = "Pieter Paul Rubens",
      LocLat = 51.219326,
      LocLong = 4.401576,
      LocDescription = "Groenplaats, standbeeld Pieter Paul Rubens."
      };
      var location5 = new Location()
      {
      LocName = "Politiekantoor",
      LocLat = 51.230754,
      LocLong = 4.4174065,
      LocDescription = "Politiekantoor"
      };
      globalContext.Add(location2);
      globalContext.Add(location3);
      globalContext.Add(location4);
      globalContext.Add(location5);

      var suspect0 = new Suspect()
      {
      // SuspectId = 1,
      SusName = "Miss Scarlett",
      SusWeapon = "Rope",
      SusDescription = "Ms. Vivienne Sakura Scarlet",
      SusImgUrl = "https://i.pinimg.com/originals/95/ce/3d/95ce3da06af8b1c09a4b2d4fa603b7a0.jpg",
      };
      var suspect1 = new Suspect()
      {
      SusName = "Mr. Green",
      SusWeapon = "Wooden cross",
      SusDescription = "Rev. Jonathan Green.",
      SusImgUrl = "https://pbs.twimg.com/profile_images/447953368271814657/Inf33QvJ.jpeg",
      };
      var suspect2 = new Suspect()
      {
      SusName = "Colonel Mustard",
      SusWeapon = "Gun",
      SusDescription = "Col. Michael Mustard",
      SusImgUrl = "https://static.independent.co.uk/s3fs-public/thumbnails/image/2016/07/04/08/unspecified-3.jpg?width=1368&height=912&fit=bounds&format=pjpg&auto=webp&quality=70",
      };

      var suspect3 = new Suspect()
      {
      SusName = "Dr.Orchid",
      SusWeapon = "Syringe",
      SusDescription = "A Doctor, Elegant ",
      SusImgUrl = "https://static.independent.co.uk/s3fs-public/thumbnails/image/2016/07/04/08/unspecified-4.jpg?width=1368&height=912&fit=bounds&format=pjpg&auto=webp&quality=70",
      };
      globalContext.Suspects.Add(suspect0);
      globalContext.Suspects.Add(suspect1);
      globalContext.Suspects.Add(suspect2);
      globalContext.Suspects.Add(suspect3);

      var clue0 = new Clue()
      {
      ClueName = "RansomPuzzle"
      };
      var clue1 = new Clue()
      {
      ClueName = "ARKnife"
      };
      var clue2 = new Clue()
      {
      ClueName = "ARRope"
      };
      globalContext.Clues.Add(clue0);
      globalContext.Clues.Add(clue1);
      globalContext.Clues.Add(clue2);
      globalContext.SaveChanges();
      }
      }


      This is first test



         [Fact]
      public void Throw_AppExceptionTooManyItems_Over8ItemsAdded()
      {
      var options = new DbContextOptionsBuilder<GameContext>().UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options;

      using (var globalContext = new GameContext(options))
      {
      gameService = new GameService(globalContext);
      //act and assert
      Exception ex = Assert.Throws<AppException>(() => gameService.CreateGame(1, 2));
      Assert.Contains("between", ex.Message);
      }
      }


      2nd test. Here (I think) I make another db, but doesn't this just leave the data from previous test laying around? So if I were to make alot of tests, woudn't it slow down the test process?



         [Fact]
      public void Throw_AppExceptionWrongUser()
      {
      var options = new DbContextOptionsBuilder<GameContext>().UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options;

      using (var globalContext = new GameContext(options))
      {
      gameService = new GameService(globalContext);
      //act and assert
      Exception ex = Assert.Throws<AppException>(() => gameService.CreateGame(2, 3));
      Assert.Equal("User does not exist.", ex.Message);
      }
      }
      }


      }



      Are there better ways to go about this?










      share|improve this question














      I'm trying to implement unit tests for a rest api I created. When I run the tests separately, they pass. But when I try to run all of them in 1 go, only 1 passes.



      I know it has something to do with way I try to use the same data in evry test. I found a solution by using a new database(name) for every test. But I was wondering if this is the correct way to go about it? Since I think there has to be a cleaner way. I looked into the IDisposable method, but I coudn't get it to work.



      This is how I put data in the db to test against:



      public class GameTestShould
      {
      private static GameService gameService;

      private readonly DbContextOptions<GameContext> options;
      public readonly Game testGame;
      public readonly User testUser;
      public Location testLocation;


      public GameTestShould()
      {
      //Arrange For the all tests
      options = new DbContextOptionsBuilder<GameContext>().UseInMemoryDatabase(databaseName: "GameTestDB").Options;
      //arrange
      using (var globalContext = new GameContext(options))
      {
      gameService = new GameService(globalContext);

      var testUser = new User()
      {
      Username = "tempUser",
      Password = "123456"
      };
      globalContext.Users.Add(testUser);
      var location2 = new Location()
      {
      LocName = "Standbeeld Stadhuis",
      LocLat = 51.220884,
      LocLong = 4.398995,
      LocDescription = "Standbeeld Vrijheid blijheid nabij stadhuis."
      };
      var location3 = new Location()
      {
      LocName = "Het Steen",
      LocLat = 51.222773,
      LocLong = 4.397367,
      LocDescription = "Het Steen"
      };
      var location4 = new Location()
      {
      LocName = "Pieter Paul Rubens",
      LocLat = 51.219326,
      LocLong = 4.401576,
      LocDescription = "Groenplaats, standbeeld Pieter Paul Rubens."
      };
      var location5 = new Location()
      {
      LocName = "Politiekantoor",
      LocLat = 51.230754,
      LocLong = 4.4174065,
      LocDescription = "Politiekantoor"
      };
      globalContext.Add(location2);
      globalContext.Add(location3);
      globalContext.Add(location4);
      globalContext.Add(location5);

      var suspect0 = new Suspect()
      {
      // SuspectId = 1,
      SusName = "Miss Scarlett",
      SusWeapon = "Rope",
      SusDescription = "Ms. Vivienne Sakura Scarlet",
      SusImgUrl = "https://i.pinimg.com/originals/95/ce/3d/95ce3da06af8b1c09a4b2d4fa603b7a0.jpg",
      };
      var suspect1 = new Suspect()
      {
      SusName = "Mr. Green",
      SusWeapon = "Wooden cross",
      SusDescription = "Rev. Jonathan Green.",
      SusImgUrl = "https://pbs.twimg.com/profile_images/447953368271814657/Inf33QvJ.jpeg",
      };
      var suspect2 = new Suspect()
      {
      SusName = "Colonel Mustard",
      SusWeapon = "Gun",
      SusDescription = "Col. Michael Mustard",
      SusImgUrl = "https://static.independent.co.uk/s3fs-public/thumbnails/image/2016/07/04/08/unspecified-3.jpg?width=1368&height=912&fit=bounds&format=pjpg&auto=webp&quality=70",
      };

      var suspect3 = new Suspect()
      {
      SusName = "Dr.Orchid",
      SusWeapon = "Syringe",
      SusDescription = "A Doctor, Elegant ",
      SusImgUrl = "https://static.independent.co.uk/s3fs-public/thumbnails/image/2016/07/04/08/unspecified-4.jpg?width=1368&height=912&fit=bounds&format=pjpg&auto=webp&quality=70",
      };
      globalContext.Suspects.Add(suspect0);
      globalContext.Suspects.Add(suspect1);
      globalContext.Suspects.Add(suspect2);
      globalContext.Suspects.Add(suspect3);

      var clue0 = new Clue()
      {
      ClueName = "RansomPuzzle"
      };
      var clue1 = new Clue()
      {
      ClueName = "ARKnife"
      };
      var clue2 = new Clue()
      {
      ClueName = "ARRope"
      };
      globalContext.Clues.Add(clue0);
      globalContext.Clues.Add(clue1);
      globalContext.Clues.Add(clue2);
      globalContext.SaveChanges();
      }
      }


      This is first test



         [Fact]
      public void Throw_AppExceptionTooManyItems_Over8ItemsAdded()
      {
      var options = new DbContextOptionsBuilder<GameContext>().UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options;

      using (var globalContext = new GameContext(options))
      {
      gameService = new GameService(globalContext);
      //act and assert
      Exception ex = Assert.Throws<AppException>(() => gameService.CreateGame(1, 2));
      Assert.Contains("between", ex.Message);
      }
      }


      2nd test. Here (I think) I make another db, but doesn't this just leave the data from previous test laying around? So if I were to make alot of tests, woudn't it slow down the test process?



         [Fact]
      public void Throw_AppExceptionWrongUser()
      {
      var options = new DbContextOptionsBuilder<GameContext>().UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options;

      using (var globalContext = new GameContext(options))
      {
      gameService = new GameService(globalContext);
      //act and assert
      Exception ex = Assert.Throws<AppException>(() => gameService.CreateGame(2, 3));
      Assert.Equal("User does not exist.", ex.Message);
      }
      }
      }


      }



      Are there better ways to go about this?







      asp.net-core xunit






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jan 2 at 0:49









      Sacerdos1Sacerdos1

      73




      73
























          1 Answer
          1






          active

          oldest

          votes


















          0














          You need to give each test a new database otherwise, as you have seen, the db is reused for each test and can affect the results.



          You can read the docs which uses a new InMemoryDatabase for each test. I give the database the same name as the test method (just for clarity).



          You could move your db code to a private method and re-use that in each test e.g.



          [Fact]
          public void Throw_AppExceptionWrongUser()
          {
          var options = new DbContextOptionsBuilder<GameContext>().UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options;

          using (var globalContext = CreateNewContext(options))
          {
          gameService = new GameService(globalContext);
          //act and assert
          Exception ex = Assert.Throws<AppException>(() => gameService.CreateGame(2, 3));
          Assert.Equal("User does not exist.", ex.Message);
          }
          }
          }

          private GameContext CreateNewContext(DbContextOptions options)
          {
          var globalContext = new GameContext(options);

          var testUser = new User()
          {
          Username = "tempUser",
          Password = "123456"
          };
          globalContext.Users.Add(testUser);

          return globalContext;
          }


          Performance shouldn't be affected that much, unless you are populating the in memory database with lots of data (but based on your example code that doesn't seem a problem). One way to find out is to write the tests and measure it :-)



          If performance is an issue then you should consider only populating the database with the data you need for the specific test. I would recommend looking at the Builder pattern for populating the database if you want to go down that route.






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54000113%2fhow-to-run-multiple-unit-tests-using-same-data%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            You need to give each test a new database otherwise, as you have seen, the db is reused for each test and can affect the results.



            You can read the docs which uses a new InMemoryDatabase for each test. I give the database the same name as the test method (just for clarity).



            You could move your db code to a private method and re-use that in each test e.g.



            [Fact]
            public void Throw_AppExceptionWrongUser()
            {
            var options = new DbContextOptionsBuilder<GameContext>().UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options;

            using (var globalContext = CreateNewContext(options))
            {
            gameService = new GameService(globalContext);
            //act and assert
            Exception ex = Assert.Throws<AppException>(() => gameService.CreateGame(2, 3));
            Assert.Equal("User does not exist.", ex.Message);
            }
            }
            }

            private GameContext CreateNewContext(DbContextOptions options)
            {
            var globalContext = new GameContext(options);

            var testUser = new User()
            {
            Username = "tempUser",
            Password = "123456"
            };
            globalContext.Users.Add(testUser);

            return globalContext;
            }


            Performance shouldn't be affected that much, unless you are populating the in memory database with lots of data (but based on your example code that doesn't seem a problem). One way to find out is to write the tests and measure it :-)



            If performance is an issue then you should consider only populating the database with the data you need for the specific test. I would recommend looking at the Builder pattern for populating the database if you want to go down that route.






            share|improve this answer




























              0














              You need to give each test a new database otherwise, as you have seen, the db is reused for each test and can affect the results.



              You can read the docs which uses a new InMemoryDatabase for each test. I give the database the same name as the test method (just for clarity).



              You could move your db code to a private method and re-use that in each test e.g.



              [Fact]
              public void Throw_AppExceptionWrongUser()
              {
              var options = new DbContextOptionsBuilder<GameContext>().UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options;

              using (var globalContext = CreateNewContext(options))
              {
              gameService = new GameService(globalContext);
              //act and assert
              Exception ex = Assert.Throws<AppException>(() => gameService.CreateGame(2, 3));
              Assert.Equal("User does not exist.", ex.Message);
              }
              }
              }

              private GameContext CreateNewContext(DbContextOptions options)
              {
              var globalContext = new GameContext(options);

              var testUser = new User()
              {
              Username = "tempUser",
              Password = "123456"
              };
              globalContext.Users.Add(testUser);

              return globalContext;
              }


              Performance shouldn't be affected that much, unless you are populating the in memory database with lots of data (but based on your example code that doesn't seem a problem). One way to find out is to write the tests and measure it :-)



              If performance is an issue then you should consider only populating the database with the data you need for the specific test. I would recommend looking at the Builder pattern for populating the database if you want to go down that route.






              share|improve this answer


























                0












                0








                0







                You need to give each test a new database otherwise, as you have seen, the db is reused for each test and can affect the results.



                You can read the docs which uses a new InMemoryDatabase for each test. I give the database the same name as the test method (just for clarity).



                You could move your db code to a private method and re-use that in each test e.g.



                [Fact]
                public void Throw_AppExceptionWrongUser()
                {
                var options = new DbContextOptionsBuilder<GameContext>().UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options;

                using (var globalContext = CreateNewContext(options))
                {
                gameService = new GameService(globalContext);
                //act and assert
                Exception ex = Assert.Throws<AppException>(() => gameService.CreateGame(2, 3));
                Assert.Equal("User does not exist.", ex.Message);
                }
                }
                }

                private GameContext CreateNewContext(DbContextOptions options)
                {
                var globalContext = new GameContext(options);

                var testUser = new User()
                {
                Username = "tempUser",
                Password = "123456"
                };
                globalContext.Users.Add(testUser);

                return globalContext;
                }


                Performance shouldn't be affected that much, unless you are populating the in memory database with lots of data (but based on your example code that doesn't seem a problem). One way to find out is to write the tests and measure it :-)



                If performance is an issue then you should consider only populating the database with the data you need for the specific test. I would recommend looking at the Builder pattern for populating the database if you want to go down that route.






                share|improve this answer













                You need to give each test a new database otherwise, as you have seen, the db is reused for each test and can affect the results.



                You can read the docs which uses a new InMemoryDatabase for each test. I give the database the same name as the test method (just for clarity).



                You could move your db code to a private method and re-use that in each test e.g.



                [Fact]
                public void Throw_AppExceptionWrongUser()
                {
                var options = new DbContextOptionsBuilder<GameContext>().UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString()).Options;

                using (var globalContext = CreateNewContext(options))
                {
                gameService = new GameService(globalContext);
                //act and assert
                Exception ex = Assert.Throws<AppException>(() => gameService.CreateGame(2, 3));
                Assert.Equal("User does not exist.", ex.Message);
                }
                }
                }

                private GameContext CreateNewContext(DbContextOptions options)
                {
                var globalContext = new GameContext(options);

                var testUser = new User()
                {
                Username = "tempUser",
                Password = "123456"
                };
                globalContext.Users.Add(testUser);

                return globalContext;
                }


                Performance shouldn't be affected that much, unless you are populating the in memory database with lots of data (but based on your example code that doesn't seem a problem). One way to find out is to write the tests and measure it :-)



                If performance is an issue then you should consider only populating the database with the data you need for the specific test. I would recommend looking at the Builder pattern for populating the database if you want to go down that route.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jan 2 at 1:24









                Simply GedSimply Ged

                2,64621523




                2,64621523
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54000113%2fhow-to-run-multiple-unit-tests-using-same-data%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Monofisismo

                    Angular Downloading a file using contenturl with Basic Authentication

                    Olmecas