簡體   English   中英

C#實體框架內存數據庫如何在單元測試中跳過或測試標量函數

[英]C# Entity Framework in-memory database how to skip or test the scalar function in unit test

我的實體上下文中有以下DbFunction

[DbFunction("fn_Replicate")]
public static string Replicate(string padChar, int patternLength, string value) => throw new Exception;

SQL服務器功能:

CREATE FUNCTION [dbo].[fn_Replicate]
    (@ReplicateChar CHAR(1) = '0',
     @PatternLength INT,
     @FieldValue NVARCHAR(10))
RETURNS NVARCHAR(10)
AS
BEGIN
    DECLARE @Result NVARCHAR(10)

    SELECT @Result = REPLICATE(@ReplicateChar, @PatternLength - LEN(@FieldValue)) + @FieldValue

    RETURN @Result
END

在我的 C# 代碼中:

    if (query.Any(usr => OrganisationContextNew.Replicate("0", (EmployeNumberPatternLength - usr.PersonNumber.Length), usr.PersonNumber) ==
                              OrganisationContextNew.Replicate("0", (EmployeNumberPatternLength - employeeNumber.Length), employeeNumber)
                            && usr.CompanyCode.Code.Equals(companyCode, StringComparison.OrdinalIgnoreCase)))

我正在使用內存數據庫,當我運行單元測試時,它因函數失敗並拋出上下文中定義的新異常。

我的測試設置是:

    [SetUp]
    public virtual void Setup()
    {
        _fixture = new Fixture().UseDefaultBehaviors(skipNonPrimitiveMembers: true);

        var options = new DbContextOptionsBuilder<OrganisationContextNew>()
            .UseInMemoryDatabase(Guid.NewGuid().ToString())
            .Options;
        _context = new OrganisationContextNew(options);
    }

誰能幫我這個?

它適用於以下實現:

    [DbFunction("fn_Replicate")]
    public static string Replicate(char padChar, int patternLength, string value) 
    {
        var padLength = patternLength - value.Length;

        return padLength >= 0 ? value : value.PadLeft(padLength, padChar);
    }
    [DbFunction("fn_Replicate")]
    public static string Replicate(char padChar, int patternLength, string value) 
    {
        var padLength = patternLength - value.Length;

        return padLength >= 0 ? value : value.PadLeft(padLength, padChar);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM