3

我想在下面的代码中测试 FindPolicyToBeResent()。我有几个可用的选项,但想知道如果我的方法(即最后一个选项可以),其他人将如何处理这种情况?

  • 公开 FindPolicyToBeResent()。这不是一个选项,因为它仅出于测试原因而公开实现并使接口混乱
  • 仅使用公共 API 进行单元测试,但这可能很困难,因为我从不直接在 return 语句中公开我正在过滤的集合,并且出于安全原因不能这样做。这意味着我只能进行有限的测试
  • 通常我会在这种情况下将代码分解成一个新对象,但在这种情况下感觉不对,我无法预见这个过滤器会在系统中的其他任何地方重用,所以它不会比将方法公开和之前更好任何人都用单一责任棒打我(这是合理的),编码是一种平衡行为,我觉得它会打破保持简单的原则。感觉就像是创建一个类来为测试服务,而不是它实际上具有单独的单一职责。再加上它会导致文件和类膨胀。
  • 我可以使代码成为 IEnumerable 的扩展方法,这将使其可测试,但我再次无法预见此过滤器会在其他任何地方使用,因此如果它保留在此类中会更有意义
  • 最后一个选项并且更喜欢但可能被视为有点 hack 是使用 verify() 进一步测试 documentResenderRepository.CanPolicyBeResent(policy.Id) 的模拟,以查看它被击中了多少次。我不确定这是否是个好主意?想法?

我的偏好是最后一个选项,但它确实感觉有点脏,我在底部有一个例子

public class DocumentResendService : IDocumentResendService
{
    #region Member Variables
    ...
    #endregion


    #region Constructors
    ...
    #endregion


    #region Accessors
    ...
    #endregion

    #region Methods
    public IDocumentResendResponse ResendDocuments()
    {
        if (!IsInputsValid())
        {
            return response;
        }


        RecordRequestAttempt();

        if (RequestLimitIsReached())
        {
            return response;
        }


        FindPolicyToBeResent();


        if(PolicyCanNotBeResent())
        {
            return response;
        }

        RequestDocumentToBeResent();

        return response;
    }


    private bool IsInputsValid()
    {
        ..
    }


    private void RecordRequestAttempt()
    {
        ...
    }


    private bool RequestLimitIsReached()
    {
        ...
    }

    // I want to test this method which basically just filters the policies
    private void FindPolicyToBeResent()
    {
        var allPolicies = policyDocumentRepository.GetPolicy(AgentCode, Email, PostCode, SearchDate, BirthDate);

        policies = allPolicies.Where(currentPolicy => currentPolicy.IsActive() || currentPolicy.IsInTheFuture());

        if (policies.Count() == 0 )
        {
            policies = allPolicies.FilterToPolicyThatHasEndedMostRecently();          
        }
     }


    private bool PolicyCanNotBeResent()
    {
        if (policies == null || !policies.Any())
        {
            response.Add(ErrorCode.PolicyCanNotBeFound);

            return true;
        }

        foreach (var policy in policies)
        {
           // I could mock this line and use a verify here which policy id's are passed in
            if (documentResenderRepository.CanPolicyBeResent(policy.Id) == false)
            {
                response.Add(ErrorCode.UnableToResendDocument);
            }  
        }

        return response.Errors.Any();
    }


    private void RequestDocumentToBeResent()
    {
        ...
    }

    #endregion
}

这是最后一个选项的单元测试解决方案,但是

[TestFixture]
public class FindPolicyToBeResentTest : DocumentResenderTestsBase
{
    private readonly List<Policy> allPolicies = new List<Policy>();

    public FindPolicyToBeResentTest()
    {
        var day = -250;

        for (int i = 1; i < 6; i++)
        {
            var policy = new Policy
            {
                Id = i,
                StartDate = DateTime.Now.AddDays(day)
            };
            day = day + 100;
            policy.EndDate = DateTime.Now.AddDays(day);
            allPolicies.Add(policy);
        }
    }

    private void SetUpDocumentResender(IEnumerable<Policy> policies)
    {


        SetUpObjectDefaultsForDocumentResenderCreation();

        policyRepositoryMock.Setup(y => y.GetPolicy(It.IsAny<string>(),
                                                    It.IsAny<string>(),
                                                    It.IsAny<string>(),
                                                    It.IsAny<DateTime>(),
                                                    It.IsAny<DateTime>()))
            .Returns(policies);


        documentResendService = CreateDocumentResendService();

        SetDocumentResenderDefaults();
    }


    [Test]
    public void PoliciesThatAreNotActiveOrAreInThePastShouldBeFilteredOut()
    {
        SetUpDocumentResender(allPolicies);

        documentResendService.ResendDocuments();

        foreach (var policy in allPolicies)
        {
            if (policy.IsActive() || policy.IsInTheFuture())
            {
                documentResenderRepositoryMock.Verify(x => x.CanPolicyBeResent(policy.Id), Times.AtLeastOnce());
            }
            else
            {
                documentResenderRepositoryMock.Verify(x => x.CanPolicyBeResent(policy.Id), Times.Never());
            }
        }
    }

    [Test]
    public void IfNoPoliciesAreFoundThatAreSuitableForDocumentResendingThenGetThePolicyThatHasMostRecentlyExpired()
    {
        var unsuitablePolicies = allPolicies.Where(x => x.IsActive() == false && x.IsInTheFuture() == false).OrderBy(x => x.EndDate);

        var policyWithClosestToEndDateToNow = unsuitablePolicies.ToList().Last();

        SetUpDocumentResender(unsuitablePolicies);

        documentResendService.ResendDocuments();

        documentResenderRepositoryMock.Verify(x => x.CanPolicyBeResent(policyWithClosestToEndDateToNow.Id), Times.AtLeastOnce());

        foreach (var policy in allPolicies.Where(policy => policy != policyWithClosestToEndDateToNow))
        {
            documentResenderRepositoryMock.Verify(x => x.CanPolicyBeResent(policy.Id), Times.Never());
        }
    }
}
4

2 回答 2

5

通过公共方法测试私有方法很好。如果您的代码足够模块化,则不应该有太多的设置代码才能使条件正确以进入您的私有方法。如果您确实发现自己设置了很多东西只是为了进入您的私有方法,那么您很可能在一堂课上做的太多了。

在您的情况下,我很想遵循您的第 3 点),并创建一个 PolicyFinder : IPolicyFinder 类。也许你现在不需要重用它,它让你的代码在未来更容易修改,让两个类更容易测试

(见http://en.wikipedia.org/wiki/Single_responsibility_principle

编辑:我没有完全阅读你的 3)要点,很抱歉用单一责任棒打你;)

于 2013-02-04T15:23:57.583 回答
0

您可以将方法标记为内部方法,而不是私有方法,然后使用 AssemblyInfo.cs 文件中的InternalsVisibleTo属性来允许单元测试程序集访问这些内部方法。例如,我的程序集 OVReadySDK 的 AssemblyInfo 文件中的此语句:

[assembly: InternalsVisibleTo("OVReadySDKUT, PublicKey=002400000480...5baacad")]

允许我的单元测试程序集 OVReadySDKUT 中的测试方法访问 OVReadySDK 中的类和方法,就好像测试方法是相同的程序集一样。

通过搜索“InternalsVisibleTo 单元测试”,您可以找到很多该技术的示例。InternalsVisibleTo请注意,如果您的程序集已签名,则需要在语句中提供公钥参数。

于 2013-02-04T16:15:59.653 回答