我在存盤庫中有一個接收Expression作為引數的方法,并且該方法的結果應該按該運算式進行過濾。問題是,當我嘗試測驗此方法時,它并沒有給我過濾的結果:
我正在測驗的服務方法
public async Task<Response<IEnumerable<AirlineDto>>> GetAllAsync()
{
try
{
var airlines = await _airlineRepository.GetAsync(x => x.Status); // call to the real repo
... // some logic
}
... // exception handling
}
方法設定,MockAirlineRepository是一個模擬AirlineRepository
public MockAirlineRepository MockGetAll()
{
Setup(x => x.GetAsync(It.IsAny<Expression<Func<Airline, bool>>>()))
.ReturnsAsync(GetTestAirlines);
return this;
}
private static IEnumerable<Airline> GetTestAirlines()
{
var airlines = new List<Airline>
{
new()
{
Id = Guid.NewGuid(),
Name = "Test One",
Status = true
},
new()
{
Id = Guid.NewGuid(),
Name = "Test Two",
Status = true
},
new()
{
Id = Guid.NewGuid(),
Name = "Test Three",
Status = false // notice that this Airline Status is false, so,
// the count of the retrieved values should be 2
}
};
return airlines;
}
測驗
[Fact]
public void AirlineService_GetAll_ReturnsAirlines()
{
//Arrange
var mockAirlineRepo = new MockAirlineRepository().MockGetAll();
var airlineService = new AirlineService(mockAirlineRepo.Object, _airlineMapper);
//Act
var result = airlineService.GetAllAsync().Result.Data;
//Assert
var airlineDtoList = result.ToList();
Assert.NotEmpty(airlineDtoList);
Assert.Equal(2, airlineDtoList.Count); // assert fails, because airlineDtoList.Count is 3
mockAirlineRepo.VerifyGetAllAirlines(Times.Once());
}
uj5u.com熱心網友回復:
讓我們從基礎開始:
- Dummy:回傳虛假資料的簡單代碼
- Fake:一種可行的替代方案,可以走捷徑
- 存根:具有預定義資料的自定義邏輯
- 模擬:具有期望的自定義??邏輯(互動式存根)
- Shim:運行時的自定義邏輯(用委托替換靜態)
- 間諜:攔截器來記錄通話
因此,您的模擬是一個互動式存根,這意味著它可以根據接收到的輸入回傳不同的輸出。在您的Setup電話中,您做了以下宣告:無論我收到什么作為過濾器運算式,我都應該始終回傳整個串列
如果要應用過濾器,請更改設定
.Setup(x => x.GetAsync(It.IsAny<Expression<Func<Airline, bool>>>()))
.ReturnsAsync(filter => GetTestAirlines.Where(filter));
現在,如果您斷言,airlineDtoList.Count那么它將回傳 2。但在這種情況下,您不是在測驗GetAllAsync函式,而是在測驗您的模擬。
所以,我寧愿花更多的時間來測驗// some logic
您還可以利用async-await在您的測驗中
[Fact]
public Task AirlineService_GetAll_ReturnsAirlines()
{
//Arrange
var mockAirlineRepo = new MockAirlineRepository().MockGetAll();
var airlineService = new AirlineService(mockAirlineRepo.Object, _airlineMapper);
//Act
var response = await airlineService.GetAllAsync();
var result = response.Data;
//Assert
...
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/489646.html
上一篇:如何使用JMeter在同一回圈中回圈具有不同間隔的采樣器
下一篇:在“div”旁邊放置文本
