Avoid HasData Seed DbContext in EF Core 2.2 during Unit TestsHow should I unit test threaded code?Unit Testing C CodeIs Unit Testing worth the effort?What's the best strategy for unit-testing database-driven applications?JavaScript unit test tools for TDDWhat is Unit test, Integration Test, Smoke test, Regression Test?Improve INSERT-per-second performance of SQLite?How are people unit testing with Entity Framework 6, should you bother?Create unit tests in ASP.NET coreHow to unit test exception filter in web API ASP.Net core. Dont want to mock the onException method

How can Paypal know my card is being used in another account?

Correct word for a little toy that always stands up?

Create two random teams from a list of players

How can flights operated by the same company have such different prices when marketed by another?

If the Moon were impacted by a suitably sized meteor, how long would it take to impact the Earth?

Why would an invisible personal shield be necessary?

How did astronauts using rovers tell direction without compasses on the Moon?

Is it possible to tell if a child will turn into a Hag?

Why did I lose on time with 3 pawns vs Knight. Shouldn't it be a draw?

Why are we moving in circles with a tandem kayak?

Why are prop blades not shaped like household fan blades?

Patio gate not at right angle to the house

How should I quote American English speakers in a British English essay?

Should I put my name first, or last in the team members list

Can machine learning learn a function like finding maximum from a list?

What is my clock telling me to do?

Are all French verb conjugation tenses and moods practical and efficient?

May a hotel provide accommodation for fewer people than booked?

Embedded C - Most elegant way to insert a delay

Raindrops in Python

How do I make my photos have more impact?

Exploiting the delay when a festival ticket is scanned

How to have poached eggs in "sphere form"?

Scam? Checks via Email



Avoid HasData Seed DbContext in EF Core 2.2 during Unit Tests


How should I unit test threaded code?Unit Testing C CodeIs Unit Testing worth the effort?What's the best strategy for unit-testing database-driven applications?JavaScript unit test tools for TDDWhat is Unit test, Integration Test, Smoke test, Regression Test?Improve INSERT-per-second performance of SQLite?How are people unit testing with Entity Framework 6, should you bother?Create unit tests in ASP.NET coreHow to unit test exception filter in web API ASP.Net core. Dont want to mock the onException method






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















In my ASP.Net CORE 2.2/EF Core 2.2 web API app, I have a HasData() method in my DbContext to seed the DB with some standard data that I use. However, I don't want to use that data when running my xUnit tests.



My unit tests use the Sqlite in-memory provider and as part of that process, it requires a call to EnsureCreated(). Well, EnsureCreated() calls OnModelCreating() which calls HasData(), so my unit test context now contains all of my HasData seed data, which I don't want. I want to seed my unit tests with different, very specific data.



Because EnsureCreated() seeds the context, and then I try adding my unit test specific seed data, I end up with both sets of data in my test DbContext and my tests fail.



How can I bypass the HasData call for my unit tests?










share|improve this question


























  • I also encountered this issue but can't find a way solve it. I just settled into using the InMemory Database Provider for some of my tests.

    – Jan Paolo Go
    Mar 26 at 21:01











  • @PaoloGo, I started with the regular InMemory provider but ran into an issue with that because it doesn't reset the Identity increment between tests running in parallel, so I was getting unpredictable primary key IDs.

    – Bryan Lewis
    Mar 26 at 21:05






  • 1





    Ah also got issue on that lol. You can workaround by testing against the inserted entity's PK instead of a constant value. e.g. var foo = ctx.Add(new Foo()); ... Assert.Equal(foo.Id, actualId); Should be a non-issue on EF Core v3

    – Jan Paolo Go
    Mar 26 at 21:10







  • 1





    Please let me know if you get a solution on the original issue though. We could open an issue on the repo otherwise :)

    – Jan Paolo Go
    Mar 26 at 21:15











  • Another workaround for the original issue is to remove the seed explicitly e.g. ctx.RemoveRange(ctx.Foo);

    – Jan Paolo Go
    Mar 28 at 2:20

















1















In my ASP.Net CORE 2.2/EF Core 2.2 web API app, I have a HasData() method in my DbContext to seed the DB with some standard data that I use. However, I don't want to use that data when running my xUnit tests.



My unit tests use the Sqlite in-memory provider and as part of that process, it requires a call to EnsureCreated(). Well, EnsureCreated() calls OnModelCreating() which calls HasData(), so my unit test context now contains all of my HasData seed data, which I don't want. I want to seed my unit tests with different, very specific data.



Because EnsureCreated() seeds the context, and then I try adding my unit test specific seed data, I end up with both sets of data in my test DbContext and my tests fail.



How can I bypass the HasData call for my unit tests?










share|improve this question


























  • I also encountered this issue but can't find a way solve it. I just settled into using the InMemory Database Provider for some of my tests.

    – Jan Paolo Go
    Mar 26 at 21:01











  • @PaoloGo, I started with the regular InMemory provider but ran into an issue with that because it doesn't reset the Identity increment between tests running in parallel, so I was getting unpredictable primary key IDs.

    – Bryan Lewis
    Mar 26 at 21:05






  • 1





    Ah also got issue on that lol. You can workaround by testing against the inserted entity's PK instead of a constant value. e.g. var foo = ctx.Add(new Foo()); ... Assert.Equal(foo.Id, actualId); Should be a non-issue on EF Core v3

    – Jan Paolo Go
    Mar 26 at 21:10







  • 1





    Please let me know if you get a solution on the original issue though. We could open an issue on the repo otherwise :)

    – Jan Paolo Go
    Mar 26 at 21:15











  • Another workaround for the original issue is to remove the seed explicitly e.g. ctx.RemoveRange(ctx.Foo);

    – Jan Paolo Go
    Mar 28 at 2:20













1












1








1








In my ASP.Net CORE 2.2/EF Core 2.2 web API app, I have a HasData() method in my DbContext to seed the DB with some standard data that I use. However, I don't want to use that data when running my xUnit tests.



My unit tests use the Sqlite in-memory provider and as part of that process, it requires a call to EnsureCreated(). Well, EnsureCreated() calls OnModelCreating() which calls HasData(), so my unit test context now contains all of my HasData seed data, which I don't want. I want to seed my unit tests with different, very specific data.



Because EnsureCreated() seeds the context, and then I try adding my unit test specific seed data, I end up with both sets of data in my test DbContext and my tests fail.



How can I bypass the HasData call for my unit tests?










share|improve this question
















In my ASP.Net CORE 2.2/EF Core 2.2 web API app, I have a HasData() method in my DbContext to seed the DB with some standard data that I use. However, I don't want to use that data when running my xUnit tests.



My unit tests use the Sqlite in-memory provider and as part of that process, it requires a call to EnsureCreated(). Well, EnsureCreated() calls OnModelCreating() which calls HasData(), so my unit test context now contains all of my HasData seed data, which I don't want. I want to seed my unit tests with different, very specific data.



Because EnsureCreated() seeds the context, and then I try adding my unit test specific seed data, I end up with both sets of data in my test DbContext and my tests fail.



How can I bypass the HasData call for my unit tests?







sqlite unit-testing asp.net-core entity-framework-core xunit






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 26 at 21:07







Bryan Lewis

















asked Mar 26 at 20:52









Bryan LewisBryan Lewis

1,5693 gold badges22 silver badges33 bronze badges




1,5693 gold badges22 silver badges33 bronze badges















  • I also encountered this issue but can't find a way solve it. I just settled into using the InMemory Database Provider for some of my tests.

    – Jan Paolo Go
    Mar 26 at 21:01











  • @PaoloGo, I started with the regular InMemory provider but ran into an issue with that because it doesn't reset the Identity increment between tests running in parallel, so I was getting unpredictable primary key IDs.

    – Bryan Lewis
    Mar 26 at 21:05






  • 1





    Ah also got issue on that lol. You can workaround by testing against the inserted entity's PK instead of a constant value. e.g. var foo = ctx.Add(new Foo()); ... Assert.Equal(foo.Id, actualId); Should be a non-issue on EF Core v3

    – Jan Paolo Go
    Mar 26 at 21:10







  • 1





    Please let me know if you get a solution on the original issue though. We could open an issue on the repo otherwise :)

    – Jan Paolo Go
    Mar 26 at 21:15











  • Another workaround for the original issue is to remove the seed explicitly e.g. ctx.RemoveRange(ctx.Foo);

    – Jan Paolo Go
    Mar 28 at 2:20

















  • I also encountered this issue but can't find a way solve it. I just settled into using the InMemory Database Provider for some of my tests.

    – Jan Paolo Go
    Mar 26 at 21:01











  • @PaoloGo, I started with the regular InMemory provider but ran into an issue with that because it doesn't reset the Identity increment between tests running in parallel, so I was getting unpredictable primary key IDs.

    – Bryan Lewis
    Mar 26 at 21:05






  • 1





    Ah also got issue on that lol. You can workaround by testing against the inserted entity's PK instead of a constant value. e.g. var foo = ctx.Add(new Foo()); ... Assert.Equal(foo.Id, actualId); Should be a non-issue on EF Core v3

    – Jan Paolo Go
    Mar 26 at 21:10







  • 1





    Please let me know if you get a solution on the original issue though. We could open an issue on the repo otherwise :)

    – Jan Paolo Go
    Mar 26 at 21:15











  • Another workaround for the original issue is to remove the seed explicitly e.g. ctx.RemoveRange(ctx.Foo);

    – Jan Paolo Go
    Mar 28 at 2:20
















I also encountered this issue but can't find a way solve it. I just settled into using the InMemory Database Provider for some of my tests.

– Jan Paolo Go
Mar 26 at 21:01





I also encountered this issue but can't find a way solve it. I just settled into using the InMemory Database Provider for some of my tests.

– Jan Paolo Go
Mar 26 at 21:01













@PaoloGo, I started with the regular InMemory provider but ran into an issue with that because it doesn't reset the Identity increment between tests running in parallel, so I was getting unpredictable primary key IDs.

– Bryan Lewis
Mar 26 at 21:05





@PaoloGo, I started with the regular InMemory provider but ran into an issue with that because it doesn't reset the Identity increment between tests running in parallel, so I was getting unpredictable primary key IDs.

– Bryan Lewis
Mar 26 at 21:05




1




1





Ah also got issue on that lol. You can workaround by testing against the inserted entity's PK instead of a constant value. e.g. var foo = ctx.Add(new Foo()); ... Assert.Equal(foo.Id, actualId); Should be a non-issue on EF Core v3

– Jan Paolo Go
Mar 26 at 21:10






Ah also got issue on that lol. You can workaround by testing against the inserted entity's PK instead of a constant value. e.g. var foo = ctx.Add(new Foo()); ... Assert.Equal(foo.Id, actualId); Should be a non-issue on EF Core v3

– Jan Paolo Go
Mar 26 at 21:10





1




1





Please let me know if you get a solution on the original issue though. We could open an issue on the repo otherwise :)

– Jan Paolo Go
Mar 26 at 21:15





Please let me know if you get a solution on the original issue though. We could open an issue on the repo otherwise :)

– Jan Paolo Go
Mar 26 at 21:15













Another workaround for the original issue is to remove the seed explicitly e.g. ctx.RemoveRange(ctx.Foo);

– Jan Paolo Go
Mar 28 at 2:20





Another workaround for the original issue is to remove the seed explicitly e.g. ctx.RemoveRange(ctx.Foo);

– Jan Paolo Go
Mar 28 at 2:20












1 Answer
1






active

oldest

votes


















0














You could always mock the call with Mock it will provides a way to mock an interface making it so the function calls of the said mocked interface will actually be calling your mocked function. This will provide a way for you to override the function call to HasData.



Of course, this means if it isn't already using an interface for that function(s) you'll have to wrap it in one.



Here are a few useful examples to Mocking: writing unit tests with NUnit and Moq and an introduction to unit testing with mocks(using moq).



I also suspect that Theory attribute and inline data could be of use to you.
Creating parameterized tests in xUnit



Hope that helps.






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%2f55366007%2favoid-hasdata-seed-dbcontext-in-ef-core-2-2-during-unit-tests%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 could always mock the call with Mock it will provides a way to mock an interface making it so the function calls of the said mocked interface will actually be calling your mocked function. This will provide a way for you to override the function call to HasData.



    Of course, this means if it isn't already using an interface for that function(s) you'll have to wrap it in one.



    Here are a few useful examples to Mocking: writing unit tests with NUnit and Moq and an introduction to unit testing with mocks(using moq).



    I also suspect that Theory attribute and inline data could be of use to you.
    Creating parameterized tests in xUnit



    Hope that helps.






    share|improve this answer





























      0














      You could always mock the call with Mock it will provides a way to mock an interface making it so the function calls of the said mocked interface will actually be calling your mocked function. This will provide a way for you to override the function call to HasData.



      Of course, this means if it isn't already using an interface for that function(s) you'll have to wrap it in one.



      Here are a few useful examples to Mocking: writing unit tests with NUnit and Moq and an introduction to unit testing with mocks(using moq).



      I also suspect that Theory attribute and inline data could be of use to you.
      Creating parameterized tests in xUnit



      Hope that helps.






      share|improve this answer



























        0












        0








        0







        You could always mock the call with Mock it will provides a way to mock an interface making it so the function calls of the said mocked interface will actually be calling your mocked function. This will provide a way for you to override the function call to HasData.



        Of course, this means if it isn't already using an interface for that function(s) you'll have to wrap it in one.



        Here are a few useful examples to Mocking: writing unit tests with NUnit and Moq and an introduction to unit testing with mocks(using moq).



        I also suspect that Theory attribute and inline data could be of use to you.
        Creating parameterized tests in xUnit



        Hope that helps.






        share|improve this answer













        You could always mock the call with Mock it will provides a way to mock an interface making it so the function calls of the said mocked interface will actually be calling your mocked function. This will provide a way for you to override the function call to HasData.



        Of course, this means if it isn't already using an interface for that function(s) you'll have to wrap it in one.



        Here are a few useful examples to Mocking: writing unit tests with NUnit and Moq and an introduction to unit testing with mocks(using moq).



        I also suspect that Theory attribute and inline data could be of use to you.
        Creating parameterized tests in xUnit



        Hope that helps.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Apr 4 at 15:05









        Jonathan Van DamJonathan Van Dam

        3914 silver badges16 bronze badges




        3914 silver badges16 bronze badges





















            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







            Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















            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%2f55366007%2favoid-hasdata-seed-dbcontext-in-ef-core-2-2-during-unit-tests%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

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript