2017-03-16 58 views
1

我刚开始使用moq对象进行单元测试,我不确定我是否正确执行此操作,请帮助!无法在单元测试中使用moq

Public Class Mrr: IMrr 
{ 

    public int Delete(double obj) 
    { 
     int rtcode = somefunction(obj);// retreiving some code from function 
     int DeleteMrr= DeleteFunction(rtcode); // delete function executes here   
     return 0; 
    } 

} 

这里是接口

public interface IMrr 
{ 
    int Delete(double obj); 
} 

和我的测试方法是这样的。

[TestMethod()] 
public void RetrieveSaveDeleteMRR() 
{  
    var FakeObject = new Moq.Mock<IMrr>(); 
    FakeObject.Setup(x => x.Delete(It.IsAny<int>())).Returns(0); 
    var Res = FakeObject.Object.Delete(10); 
} 

这不是要去执行该方法的实际功能,它假设去那里的方法或不去。我不确定。

回答

1

如果你要测试Mrr.Delete()方法,你不应该模拟Mrr。您应该创建Mrr类的实例并调用其方法。

您通常想模拟Mrr依赖关系(在您的示例中没有),以便不调用真正的依赖关系方法。

注意:您忘记从您的界面IMrr继承Mrr

+0

HI, 我编辑我的代码,你可以告诉我你是什么人都在谈论这里真正的依赖? –

+0

请检查Moq的基本教程 - http://deanhume.com/home/blogpost/basic-introduction-to-writing-unit-tests-with-moq/16 – CodeFuller

+0

是实现的必要接口吗? –

1

在您的示例中,类Mrr没有任何依赖关系。要解释什么是依赖关系,请看以下示例。

public class Mrr: IMrr 
{ 
    // This is dependency 
    IDelete _deleteObject; 

    public Mrr(IDelete deleteObject) 
    { 
     _deleteObject = deleteObject; 
    } 

    public int Delete(double obj) 
    { 
     int rtcode = somefunction(obj); 
     int DeleteMrr = _deleteObject.DeleteFunction(rtcode); 
     return 0; 
    } 
} 

public interface IDelete 
{ 
    int DeleteFunction(int rtcode); 
} 

这种依赖传递在构造函数,因此你可以在测试中提供自己的模拟实例。

比较这种情况:

public class Mrr: IMrr 
{ 
    // This is dependency 
    IDelete _deleteObject; 

    public Mrr() 
    { 
     _deleteObject = new DeleteClass(); 
    } 
} 

每次new使用它使不可能注入自己的实现在单元测试。

测试可能看起来像这样。

[TestMethod] 
public void RetrieveSaveDeleteMRR() 
{  
    // Arange 
    int expected = 1; 
    Moq.Mock<IDelete> deleteObjectMock = new Moq.Mock<IDelete>(); 
    deleteObjectMock.Setup(x => x.DeleteFunction(It.IsAny<int>())).Returns(1000); 
    Mrr testedObject = new Mrr(deleteObjectMock.Object); 

    // Act 
    int actual = testedObject.Delete(10); 

    // Assert 
    Assert.AreEqual(expected, actual); 
}