简体   繁体   English

在MVC中使用Mock进行单元测试

[英]Unit testing using Mock in MVC

I am trying to implement an unit test for a method in my class. 我正在尝试为类中的方法实施单元测试。 How could I mock a base class indexer on the class method I am testing? 如何在正在测试的类方法上模拟基类索引器? Below code snippet should give a clear picture of my requirement. 下面的代码片段应清楚说明我的要求。

public class MyClass:MyBase
{
  public string returnString(string str1)
  {
     var xyz=base[str1];
     //My code to unit test is here
  }
}

public class MyBase
{
  public virtual string this[string str1]
  {
     return "prefix"+str1;
  }
}

I would like to stub my base class indexer with a dummy string and test my actual code. 我想用一个虚拟字符串存根我的基类索引器并测试我的实际代码。 How can I do that? 我怎样才能做到这一点? Thanks for any help on this in advance. 感谢您对此事的任何帮助。

Sree. 真是

Normally not recommended practice, but in this case "appropriate": mock your class under test. 通常不建议这样做,但在这种情况下是“适当的”:模拟正在测试的类。 Of course in this case, you'd only mock out stuff that's specific to the base class and not overridden in any way your descendant under test. 当然,在这种情况下,您只会嘲笑特定于基类的内容,而不会以任何方式覆盖您的后代。 This ensures that the base class' behavior is mocked and therefore under control of the tests when testing the descendant's methods. 这样可以确保模拟基类的行为,并因此在测试后代的方法时处于测试的控制之下。

In your example, you would create a mock of MyClass but only mock out the inherited (MyBase's) constructor, thus making sure that all other methods run "as coded", and then assert against the mocked instance. 在您的示例中,您将创建MyClass的模拟,但仅模拟继承的(MyBase的)构造函数,从而确保所有其他方法均按“已编码”运行,然后针对模拟的实例进行断言。

I don't see the reason to stub your base class, since you can mock your class under test. 我看不到对您的基类进行存根的原因,因为您可以模拟正在测试的类。 I'll show you. 我会给你看。

I added return statement to returnString() method, just for assertion to complete the test: 我在returnString()方法中添加了return语句,只是为了断言来完成测试:

public string returnString (string str1)
{
    var xyz = base [str1];
    return xyz;
}

And now the test: 现在测试:

[TestMethod, Isolated]
public void TestIndexerFake()
{
    //Arrange
    var MyClassFake = Isolate.Fake.AllInstances<MyClass>(Members.CallOriginal);
    Isolate.WhenCalled(() => MyClassFake["test"]).WillReturn("fake!");

    //Act
    MyClass target = new MyClass();
    var result = target.returnString("test");

    //Assert
    Assert.AreEqual("fake!", result);
}

I'm using Typemock Isolator and MsTest. 我正在使用Typemock隔离器和MsTest。

Hope it helps! 希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM