Mark
Mark

Reputation: 4873

Unit Testing WinForms

I'm new to programming and c#, and have been assigned the task of writing unit tests for legacy code in preparation for big DB change.

The more I read on unit testing, the more skeptical I am on my approach.

How would you approach writting a unit test for the following? Currently I've just been unit testing my Data Access Layer Methods, ensuring they return back a result? But apparently unit test are supposed to be independent of any outside environments?

How can I test my application, when almost everything is making a call to the database or stored procedure?

My Form Code:

public void button1_Click(object sender, EventArgs e)
{
    LoadAllCountries()
}

private static void LoadAllCountries()
{
    List<nsHacAppMod.ViewCountryInfo> oReturn = moBusinessServices.GetAllCountries();
}

My Data Access Layer

public List<nsAppMod.ViewCountryInfo> GetAllCountries()
{
    List<nsAppMod.ViewCountryInfo> oReturn;

    var oResult = from c in moDataContext.ViewCountryInfos
                  select c;

    oReturn = oResult.ToList();

    return oReturn;
}

My current unit test for this code, is this acceptable? If not what would you test?

[Test]
public void LoadAllCountries()
{
    hac.CatalogSamples cs = new hac.CatalogSamples();
    var countries = cs.GetAllCountries().count();

    Assert.GreaterOrEqual(countries 0);
}

Upvotes: 3

Views: 653

Answers (1)

Rick Rat
Rick Rat

Reputation: 1732

You can unit test data access things if your context is based off of an interface like IContext it can be faked, and you can then test just the code you are trying to test like the GetAllCountries() method.

However, other than the try catch, there is no actual logic to test. I look at it like this: If it is a property that has no logic in it, or methods too, it's not worth testing. Using a mocking framework like FakeItEasy I would test this method just like this:

    public class ClassToTest
{
    internal virtual MoDataContext CreateContext()
    {
        return new MoDataContext();
    }

    public List<ViewCountryInfo> GetAllCountries()
    {
        List<ViewCountryInfo> oReturn = null;

        try
        {
            var oResult = from c in this.CreateContext().ViewCountryInfos
                          select c;

            oReturn = oResult.ToList();
        }
        catch (Exception)
        {
        }

        return oReturn;
    }

    [Fact]
    public void Test_GetAllCountries_ResultCountShouldBeGreaterThan0()
    {
        var fakeData = new List<ViewCountryInfo>();
        fakeData.Add(new ViewCountryInfo());

        var sut = A.Fake<ClassToTest>();
        A.CallTo(sut).CallsBaseMethod();
        A.CallTo(() => sut.CreateContext()).Returns(fakeData);

        var result = sut.GetAllCountries();

        Assert.IsTrue(result.Count() > 0);
    }

Upvotes: 2

Related Questions