user194076
user194076

Reputation: 9017

How to write a unit test without interface implementation

I'm new to unit testing.

I have to test RefreshAmount in the following code:

private readonly int id;

private readonly IService service;

public MyClass(int id, IService service)
{    
    this.id= id;
    this.service= service;    
}

public double Number { get; private set; }

public void RefreshAmount()
{    
    Number= service.GetTotalSum(id);    
}

What would be a correct unit test to write for RefreshAmount?

Upvotes: 1

Views: 2653

Answers (2)

JWP
JWP

Reputation: 6963

Start simple attempting the "Sunny Day" or "Happy Path" first...

[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
         var service = new MyService();
         int SomeProperInteger = GetNextInteger();
         double SomeProperAmount = .50;
         var actual = service.GetTotalSum(SomeProperInteger);
         double expected = SomeProperInteger * SomeProperAmount;
         Assert.IsTrue(expected = actual, "Test Failed, Expected amount was incorrect.");

    }
    private int GetNextInteger()
    {
        throw new System.NotImplementedException();
    }
}

Start with testing a service object that will be used in production as shown above. You will have to look at the code to see what GetTotalSum is supposed to do or look at the specifications. Once the "Happy path" works then you will alter at most 1 parameter at a time using Boundaries. The Boundaries would in code above come from GetNextInteger or a list of proper values. You must write code to anticipate the expected value to compare.

After the service is validated to be working as designed, move on to the class that uses the service using the same techniques.

Upvotes: -1

BradleyDotNET
BradleyDotNET

Reputation: 61349

You need to mock IService. There are various frameworks that help automate this for you (like Moq) but here's a simple example:

public class MockService : IService
{
    public double GetTotalSum(int id)
    {
        return 10;
    }
}

Basically, a mock implements your interface but just returns hard-coded (or otherwise well-known) data. That makes it easy to know what your expected value should be! Now you can use that to do your test:

public void TestMethod()
{
    MyClass testObj = new MyClass(1, new MockService());

    testObj.RefreshAmount();
    Assert.Equals(10, testObj.Number);
}

Upvotes: 4

Related Questions