Home
Options

Problem with Xunit tests against custom DbContext

I have a script with Xunit tests that run fine against a LINQPad created DbContext, but I'm creating my own custom DbContext and the Xunit test runner is failing. I presume that I'm missing something in my custom DbContext.

I tried running the xunit script that the Query | Add XUnit Test Support menu adds and found that the problem is surfacing in it and not my own unit tests. I selected the generated connection for the xunit script and ran it without problem, but when I added the connection using my custom DbContext it output the following.

Below is the start of my DbContext class showing field, constructors and Connection property. I referred to the generated DbContext in ILSpy and the only difference is that I'm not using ConnectionHelper.CurrentCxString in my default constructor, although I did reference C:\Users\steve\AppData\Local\LINQPad\8.3.7\EF\LINQPad.Drivers.EFCore.dll in my project so I could use it, but that didn't solve the problem so I removed it again. Can anyone suggest what I might be doing wrong in my DbContext creation to cause this?

public class TypedDataContext : DbContext
{
    private string _cxString;

    public TypedDataContext()
    {
        _cxString = Util.CurrentCxString;
    }

    public TypedDataContext(string connectionString)
    {
        _cxString = connectionString;
    }

    public TypedDataContext(DbContextOptions<TypedDataContext> options)
        : base(options)
    {
    }

    [EditorBrowsable(EditorBrowsableState.Never)]
    protected DbConnection Connection => Database.GetDbConnection();

Comments

  • Options

    I should have mentioned that I'm using 8.0.5, the latest release version.

  • Options

    In the connection properties dialog, you will need to choose the option for a parameterless constructor, so your query (which subclasses the TypedDataContext) will also end up with a parameterless constructor, as required for xUnit.

    Otherwise, you could provide a parameterless constructor on a per-query basis by writing one into your query as follows:

    public UserQuery() : base ("your connection string")
    {
    }
    
  • Options

    Thanks, I'll look into these options this evening.

  • Options

    In cases where Linqpad currently does not create a parameterless constructor, would it be possible for it to also create another constructor like

    public UserQuery() : base (LINQPad.Util.CurrentCxString) {}
    

    A couple of months ago, I ran into a similar issue to this when I tried to benchmark some code in a query which used a custom TypedDataContext (and because BenchMarkDotNet can't find a parameterless constructor, it can't run and so the Waiting for first iteration to complete... status message never gets updated).

  • Options

    That makes sense, although it's a little more tricky to implement in the case that the DbContextOptions constructor is selected.

Sign In or Register to comment.