我想知道是否可以使用Moq测试是否某个方法更改了某个对象中的某些属性,该方法必须无效。
我想检查产品的属性“FlgActive”是否从true更改为false。
delete方法为void,它只是将该标志更改为false。
如果可能的话,我应该在设置中添加什么来检查?
示例:
TEST
[TestMethod]
public void DeletedProductFlagShouldBeFalse() //RN03
{
var product = new Product() { Id = 1, Name = "aaaaaa", Code = "aaaaaa", FlgActive = true };
var so = new ServiceOrder() { };
var mockProductRepository = new Mock<IProductRepository>();
mockProductRepository.Setup(p => p.Delete(product));
var mockServiceOrderRepository = new Mock<IServiceOrderRepository>();
mockServiceOrderRepository.Setup(o => o.GetProductById(product.Id)).Returns(new List<ServiceOrder> { so });
var service = new ProductService(mockProductRepository.Object, mockServiceOrderRepository.Object);
service.Delete(product);
mockProductRepository.Verify(c => c.Delete(It.IsAny<Product>()), Times.Once());
mockProductRepository.Verify((s => s.Commit()), Times.Once());
Assert.IsFalse(product.FlgActive);
}
SERVICE
public void Delete(Product product)
{
Validate(product);
repo.Delete(product);
repo.Commit();
}
REPOSITORY
public void Delete(Product product)
{
try
{
product.FlgActive = false;
Update(product);
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
答案 0 :(得分:1)
将您的标志设置为false并不是您的服务,因此您不应该从服务中测试该行为。该单元的工作是验证产品,然后将删除委托给存储库。
因此,您可以从测试中删除该部分并重命名:
[TestMethod]
public void DeletionShouldBeSentToRepository() //RN03
{
var product = new Product() { Id = 1, Name = "aaaaaa", Code = "aaaaaa", FlgActive = true };
var so = new ServiceOrder() { };
var mockProductRepository = new Mock<IProductRepository>();
mockProductRepository.Setup(p => p.Delete(product));
var mockServiceOrderRepository = new Mock<IServiceOrderRepository>();
mockServiceOrderRepository.Setup(o => o.GetProductById(product.Id)).Returns(new List<ServiceOrder> { so });
var service = new ProductService(mockProductRepository.Object, mockServiceOrderRepository.Object);
service.Delete(product);
mockProductRepository.Verify(c => c.Delete(product), Times.Once());
mockProductRepository.Verify((s => s.Commit()), Times.Once());
}
注意 :我很高兴验证我们是否将优质产品发送到了回购广告。我已将It.IsAny
替换为您之前创建的产品。
既然我们已经涵盖了您服务的职责,我们可以在repo本身中测试删除行为,它应该如下所示:
[TestMethod]
public void DeletedProductFlagShouldBeFalse() //RN03
{
var product = new Product() { Id = 1, Name = "aaaaaa", Code = "aaaaaa", FlgActive = true };
IProductRepository repository = new ProductRepository();
repository.Delete(product);
Assert.IsFalse(product.FlgActive);
}
当您进行单元测试时,仅测试当前课程的行为非常重要,而不是副作用。