简体   繁体   中英

NUnit Test with Moq and lots of missing data, is it correct?

I have the only the following input data: the interface and the class. I don't have a class which implements the interface, neither any data about the client, his id and the other data. Only the following:

public interface IService
{
double GetData(int clientId);
}

public class ClientInfo
{
   private int _clientId;
   private IService _svc;
   public double MoneySun;

   public ClientInfo(int clientId, IService svc) 
  {
   _clientId = clientId;
   _svc = svc;
  }


   public void UpdateMoney()
   {
    MoneySun = _svc.GetData(_clientId);
   }

}

And I need to write an Unit test for UpdateMoney method (taking into the account that I have only the info published above)

I wrote the following test and would like to consult whether it's correct or not?

[Test]
public void GetData()
{
    Mock<IService> moqSvc = new Mock<IService>();
    var сInfo = new ClientInfo(1, moqSvc.Object);
    сInfo.UpdateMoney();

    Assert.Greater(сInfo.MoneySun, -1); 
}

And also, doing Assert I only guess that it must be grater than -1 so I'm not completely sure if this is correct. Also I only presume that there is a clientId =1

Since you are testing a service facade / proxy, mocking the service interface will allow you to determine if the interaction with the mocked interface was correct (unit tests on the other end of the wire on the actual service will need to be done to ensure that the correct transaction was done to the client).

You can also test that the state of the sut ( ClientInfo ) is consistent before and after the call:

[Test]
public void GetData()
{
    var moqSvc = new Mock<IService>();
    // Provide some fake data to ensure that the SUT uses the return value correctly
    moqSvc.Setup(x => x.GetData(It.IsAny(int))).Returns(123.45);
    var сInfo = new ClientInfo(1, moqSvc.Object);
    // Ensure correct initial state
    Assert.AreEqual(0, cInfo.MoneySun)

    сInfo.UpdateMoney();

    // Ensure correct final state
    Assert.AreEqual(123.45, cInfo.MoneySun)
    // Ensure correct interaction with the service
    moqSvc.Verify(x => x.GetData(1), Times.Once);
    moqSvc.Verify(x => x.GetData(It.IsAny<int>(i => i != 1)), Times.Never);
}

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