gpt4 book ai didi

C# 如何在没有实现的情况下对接口(interface)方法进行单元测试

转载 作者:太空狗 更新时间:2023-10-30 00:48:56 25 4
gpt4 key购买 nike

我是单元测试和 stackoverflow 的新手。

我必须在以下界面中测试RefreshAmount:

public interface IAccountService
{
double GetAccountAmount(int accountId);
}

这是一个依赖于这个接口(interface)的类:

public class AccountObj
{
private readonly int _Id;
private readonly IService _service;
public AccountObj(int Id, IService service)
{
_Id = Id;
_service = service;
}
public double Amount { get; private set; }
public void RefreshAmount()
{
Amount = _service.GetAmount(_Id);
}
}

如何对 RefreshAmount 的行为进行单元测试?

RefreshAmount 调用 IService.GetAmount 可能会调用后端办公室,但我没有它的实现。任何关于前进道路的建议将不胜感激。(我已经阅读了最小起订量和依赖注入(inject),但我对单元测试还是个新手)

最佳答案

使用最小起订量,这是一个带注释的最小示例测试

[TestClass]
public class AccountObjUnitTests {
[TestMethod]
public void AccountObj_Given_Id_RefreshAmount_Should_Return_Expected_Amount() {

//Arrange
//creating expected values for test
var expectedId = 1;
var expectedAmount = 100D;
//mock implementation of service using Moq
var serviceMock = new Mock<IService>();
//Setup expected behavior
serviceMock
.Setup(m => m.GetAmount(expectedId))//the expected method called with provided Id
.Returns(expectedAmount)//If called as expected what result to return
.Verifiable();//expected service behavior can be verified

//the system under test
var sut = new AccountObj(expectedId, serviceMock.Object);

//Act
//exercise method under test
sut.RefreshAmount();


//Assert

//verify that expectations have been met
serviceMock.Verify(); //verify that mocked service behaved as expected
Assert.AreEqual(expectedAmount, sut.Amount);
}

//Samples class and interface to explain example
public class AccountObj {
private readonly int _Id;
private readonly IService _service;
public AccountObj(int Id, IService service) {
_Id = Id;
_service = service;
}
public double Amount { get; private set; }
public void RefreshAmount() {
Amount = _service.GetAmount(_Id);
}
}

public interface IService {
double GetAmount(int accountId);
}
}

这是同一测试的更简化版本

[TestMethod]
public void AccountInfo_RefreshAmount_Given_Id_Should_Return_Expected_Amount() {
//Arrange
//creating expected values for test
var expectedId = 1;
var expectedAmount = 100D;
//mock implementation of service using Moq with expected behavior
var serviceMock = Mock.Of<IService>(m => m.GetAmount(expectedId) == expectedAmount);
//the system under test
var sut = new AccountObj(expectedId, serviceMock);

//Act
sut.RefreshAmount();//exercise method under test

//Assert
Assert.AreEqual(expectedAmount, sut.Amount);//verify that expectations have been met
}

关于C# 如何在没有实现的情况下对接口(interface)方法进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42274647/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com