对很难使用fakeDb制作的Sitecore项目进行单元测试?

时间:2019-01-03 18:55:30

标签: c# unit-testing sitecore

我目前正在尝试为我所做的覆盖创建一个单元测试,但是对单元测试似乎比我预期的要困难一些。

public class Extension
{
    public fallback(HttpContext context)
    {
       return new HttpContext();
    }  

    public IEnumerable<SiteDefinition> RunOn => new[]
    {
       "Some", "Dome", "Gone"
    };

    public bool AllowedOnSite(string site)
    {
        bool allowed = RunOn.Any(sd => sd.Name == site);
        return allowed;
    }

    protected bool Process(HttpContext context)
    {
        var site = Context.Site.Name;
        if (Context.Domain.Name == "sitecore" || !AllowedOnSite(site))
        {
            return fallback(context);
        } 
     ....

    }

我似乎对AllowedOnSite有问题,我可以自己对其进行单元测试,但不能作为Process的一部分,而对其余代码进行单元测试则需要它吗?

作为AllowedOnSite单元测试的一部分,我如何像往常一样包含Process

单元测试:

    [Theory]
    [CustomAutoData("Gonw")]
    public void AllowedOnSite_IncorrectSite_ReturnFalse(string site)
    {
        //arrange
        var processor = new MediaRequestExtensions();

        //act
        processor.AllowedOnSite(site);

        //assert
        Assert.False(processor.AllowedOnSite(site));
    }

这可以按预期工作,但是当我何时对Process方法进行单元测试时,我不知道如何使此条件成立?

[Theory]
[CustomAutoData("http://gonw.com","Gonw")]
public void Process_RequestURLIsIncorrect_Return(string url, string name)
{
    // Arrange
    var fakeSite = new Sitecore.FakeDb.Sites.FakeSiteContext(new Sitecore.Collections.StringDictionary
    {
        { "name", "Some" },
        { "b", "Dome" },
        { "c", "Gone" }
    });
    HttpRequest httpRequest = new HttpRequest(string.Empty, url, string.Empty);
    HttpResponse httpResponse = new HttpResponse(new StringWriter());
    HttpContext httpContext = new HttpContext(httpRequest, httpResponse);

    var processor = new MediaRequestExtensionsMock
    {
        GetHttpContextFunc = () => httpContext
    };
    using (new Db())
    {
        using (new Sitecore.Sites.SiteContextSwitcher(fakeSite))
        {
            Sitecore.Context.Site.Name = name;
            // Act
            processor.Process(httpContext);

            // Assert
            Assert.Equal(string.Empty, httpContext.Response.Output.ToString());
        }
    }
}

在此测试中,我触发了正确的if语句,但是如果我想触发下一个,则不必触发第一个,这似乎是不可能的。

该怎么办?

0 个答案:

没有答案