2014-02-23 91 views
1

我想对不返回任何内容的方法进行单元测试。我正在使用xUnit。我在谷歌搜索,但每个我看到的方法正在返回的东西。如何使用xUnit测试void方法?

这里是我的代码:

我的班级:

public class ShopRepository : BaseRepository<ShopInformation> 
{ 
    public ShopRepository(IDbContext dbContext) 
     : base(dbContext) 
    { 
    } 

    public override void Update(ShopInformation entity) 
    { 
     if(GetAll().Any()) 
      base.Update(entity); 
     else 
     base.Add(entity); 
    } 

    public ShopInformation ShopInformation() 
    { 
     return GetAll().FirstOrDefault(); 
    } 
} 

我的测试:

[Fact] 
    public void GetAllTest() 
    { 
     var data = new List<ShopInformation> 
     { 
      new ShopInformation { Name = "BBB" }, 
      new ShopInformation { Name = "ZZZ" }, 
      new ShopInformation { Name = "AAA" }, 
     }.AsQueryable(); 

     var mockSet = Mock.Create<DbSet<ShopInformation>>(); 
     Mock.Arrange(() => ((IEnumerable<ShopInformation>)mockSet).GetEnumerator()).Returns(data.GetEnumerator); 

     Mock.Arrange(() => ((IQueryable<ShopInformation>)mockSet).Provider).Returns(data.Provider); 

     Mock.Arrange(() => ((IQueryable<ShopInformation>)mockSet).Expression).Returns(data.Expression); 
     Mock.Arrange(() => ((IQueryable<ShopInformation>)mockSet).ElementType).Returns(data.ElementType); 
     Mock.Arrange(() => ((IQueryable<ShopInformation>)mockSet).GetEnumerator()).Returns(data.GetEnumerator()); 
     var interDbContext = Mock.Create<IDbContext>(); 
     interDbContext.Arrange(x => x.Set<ShopInformation>()).Returns(mockSet); 

     var companyRepository = new ShopRepository(interDbContext); 

     companyRepository.Update(new ShopInformation()); 

     //??????????????? 

    } 

我需要测试ShopRepositoryUpdate方法,以确保base.Update(entity);是调用。但不明白如何去做。

我使用:

  • 的Visual Studio 2013旗舰版。
  • 只是模拟2013.3.1015
  • 的xUnit 1.9.2

回答

0

有2级可能的解决方案:

  1. 如果更新方法修改从ShopRepository类中的任何值,你应该进行一些验证他们。

  2. 模拟出base.Update方法以基于此返回“expected”和断言。

0

您的测试被命名为GetAllTest(),所以它可能不应该测试Update()功能。

最好的方法是返回一个布尔值,如果它更新与否。

public bool Update(ShopInformation entity) 
{ 
    if(GetAll().Any()) 
    { 
     base.Update(entity); 
     return true; // True because it updated 
    } 
    else 
    { 
     base.Add(entity); 
     return false; // False because it didn't 
    } 
} 

然后你的测试可以Assert的预期答案。

// ... Setup test code 
var hasUpdated = companyRepository.Update(new ShopInformation()); 
Assert.Equal(true, hasUpdated); 

的一点要注意:如果您使用的是存储库,你应该使用Save,因为这将更新所做的更改,但也将增加新的记录,如果记录不存在。