gpt4 book ai didi

c# - Xunit 测试不适用于 mongodb 服务

转载 作者:可可西里 更新时间:2023-11-01 10:41:06 26 4
gpt4 key购买 nike

我想做一个小的 XUnit 测试,但它不工作。 (AddTest 有效,但 GetAllRestaurantsCountShouldReturnThree 无效。)

我是单元测试的新手,我不知道 Moq 以及如何使用它。

如何模拟我的 IMongoService 并获取餐厅数量?

MongoService.cs

public class MongoService : IMongoService
{

private readonly IMongoDatabase _mongoDatabase;
private readonly IMongoClient _mongoClient;

public MongoService()
{
_mongoClient = new MongoClient("mongodb://localhost:27017");
_mongoDatabase = _mongoClient.GetDatabase("Restaurant");
}

public List<RestaurantDto> GetAllRestaurants()
{
var collection = _mongoDatabase.GetCollection<RestaurantDto>("Restaurant");
return collection.Find(_ => true).ToList();
}
}

MongoServiceTest.cs

public class ReviewServiceTests
{
private List<RestaurantDto> _allRestaurants = new List<RestaurantDto>()
{
new RestaurantDto() {Name="xxx", ZipCode = "111" },
new RestaurantDto() {Name="yyy", ZipCode = "222" },
new RestaurantDto() {Name="zzz", ZipCode = "333" },
};

[Fact] //Not Working
public void GetAllRestaurantsCountShouldReturnThree()
{

var _mongoService = new Mock<IMongoService>();
_mongoService.Setup(x => x.GetAll()).Returns(_allRestaurants );
var count = _mongoService.GetAll(); //GetAll() not seeing

Assert.Equal(count, 3);

}

[Fact] //Working
public void AddTest()
{
Assert.Equal(10, Add(8, 2));
}

int Add(int a, int b)
{
return a + b;
}
}

最佳答案

您错误地使用了 Moq

[Fact]
public void GetAllRestaurantsCountShouldReturnThree() {

var mock = new Mock<IMongoService>();
mock.Setup(x => x.GetAllRestaurants()).Returns(_allRestaurants);

IMongoService mongoService = mock.Object;

var items = mongoService.GetAllRestaurants(); //Should call mocked service;
var count = items.Count;

Assert.Equal(count, 3);

}

阅读如何在他们的 Quickstart 中使用 Moq

关于c# - Xunit 测试不适用于 mongodb 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42773422/

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