简体   繁体   English

如何对该方法进行单元测试

[英]How to Unit Test this method

I'm learning unit testing. 我正在学习单元测试。 How would the following method be unit tested on VS 2010? 如何在VS 2010上对以下方法进行单元测试?

private string[] lstStrCalculatePoints()
{
    string[] lstStrPoints = new string[2];
    if (lblKPIAResult.Text.Contains("Exceeds"))
    {
       lstStrPoints[0] = "AHT";
    }

    if (lblKPIBResult.Text.Contains("Exceeds"))
    {
        lstStrPoints[1] = "QA";
    }

    return lstStrPoints;
}

Please provide example. 请提供示例。 Thanks! 谢谢!

I'd create two new methods: 我将创建两个新方法:

public static string GetKpiPoint(string kpiResult, string ifExceeds)
{
    return kpiResult.Contains("Exceeds") ? ifExceeds : null;
}

public static string[] CalculatePoints(string kpiAResult, string kpiBResult)
{
    return new string[] { GetKpiPoint(kpiAResult, "AHT"), GetKpiPoint(kpiBResult, "QA") };
}

then call it from your exising one: 然后从您现有的人称呼它:

private string[] lstStrCalculatePoints()
{
    return CalcualtePoints(lblKPIAResult.Text, lblKPIBResult.Text);
}

EDIT: The ways you can test this method depend on your test framework, but if you're using NUnit you can do something like: 编辑:您可以测试此方法的方法取决于您的测试框架,但是如果您使用的是NUnit,则可以执行以下操作:

[Test]
[TestCase("Exceeds", "Exceeds", new string[] { "AHT", "QA" })]
[TestCase("NoMatch", "NoMatch", new string[] { null, null })]
[TestCase("Exceeds", "NoMatch", new string[] { "AHT", null })]
[TestCase("NoMatch", "Exceeds", new string[] { null, "QA" })]
public void CalculatePointsTest(string kpiA, string kpiB, string[] expected)
{
    CollectionAssert.AreEqual(expected, CalculatePoints(kpiA, kpiB));
}

I would not test private methods directly. 我不会直接测试私有方法。

You test them indirectly by testing public methods that invoke private methods. 您可以通过测试调用私有方法的公共方法来间接测试它们。 This is to prevent you from breaking encapsulation, and it will allow you to refactor your code without having to update your tests unnecessarily. 这是为了防止破坏封装,并允许您重构代码而不必不必要地更新测试。

So long as the public interface works as defined, I do not care what the class does behind the scenes so long as I fully test the public interface's specification. 只要公共接口按定义工作,只要我完全测试公共接口的规范,我就不会在意该类在后台做什么。

PS: protected methods are a different story however, but beyond the scope of the question. PS:受保护的方法是另一回事,但超出了问题的范围。

From the lblKPI<n>Result attributes I guess you're in a WinForm application, right? lblKPI<n>Result属性中,我猜您在WinForm应用程序中,对吗? You will be better off separating your presentation logic from your view (the Form where lstStrCalculatePoints lives) and put it in a Presenter (or similar). 最好将表示逻辑与视图( lstStrCalculatePoints所在的窗体)分离,并将其放在Presenter中(或类似lstStrCalculatePoints )。 Read up on eg. 阅读例如。 Model-View-Presenter (MVP) or another MVC deriviate pattern. 模型视图呈现器(MVP)或其他MVC派生模式。 Do your unit testing on the Presenter class. 在Presenter类上进行单元测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM