2017-03-13 5 views
1

Ich möchte einen kleinen XUnit Test machen, aber es funktioniert nicht. (AddTest funktioniert aber GetAllRestaurantsCountShouldReturnThree funktioniert nicht.)Xunit Test funktioniert nicht für mongodb Service

Ich bin neu in Unit-Tests und ich weiß nicht über Moq und wie man es benutzt.

Wie kann ich meine IMongoService verspotten und Restaurant zählen?

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

Antwort

0

Sie verwenden Moq falsch

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

} 

Informieren Sie sich über die, wie Moq verwenden in ihren Quickstart

Verwandte Themen