简体   繁体   中英

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 ?

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);
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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