如何为类中的方法编写单元测试,但不调用 C# 中的类的构造函数

我想MethodA在class A. 但是,我真的不想MethodB在构造 时调用A,因为它需要很多时间来处理。


有什么办法可以处理吗? MethodB需要在其他任何事情之前调用,所以我不能将它移出 ctor(它初始化listA,listB和listC字段)。


我不知道如何为此使用模拟框架。


public Class A {


  List<int> listA;

  List<int> listB;

  List<int> listC;



  public A()

  {     

     MethodB();    // Long processing.

  }



  public List<int> GetA()

  {

      return listA;

  } 


  public List<int> GetB()

  {

      return listB;

  } 


  public List<int> GetC()

  {

      return listC;

  } 


  private void MethodB()

  {

      // Expensive initialization of list fields.

  }


  public bool MethodA(customerCollection foo)

  {

        for (int i = 0; i < customerCollection .Count; i++)

        {

            if (customerCollection[i].Name == "Something")

            {

                return true;

            }

        }


      return false;


  }

}



蓝山帝景
浏览 169回答 2
2回答

幕布斯7119047

据我所知,您MethodA不需要A实例即可运行,因此您可以将其更改为static并在没有A实例的情况下对其进行测试。但请注意,从 OOP 的角度来看,此方法在A类中没有位置(单一职责原则),因此您需要进行一些重构。

慕沐林林

虽然很清楚MethodAcan be static,但它不使用class我建议采用不同方法的任何字段,因为问题用moq和inversion-of-control标签标记。进行一些重新设计,您可以将其存档...例如,您可以通过IRepository界面公开列表,然后您可以利用 IoC 原则在单元测试中启用模拟。像这样的东西:public interface IRepository{&nbsp; &nbsp; void Init();&nbsp; &nbsp; IList<int> Get();}public Class A&nbsp;{&nbsp; &nbsp;&nbsp;&nbsp; IRepository _aRepository;&nbsp; IRepository _bRepository;&nbsp; IRepository _cRepository;&nbsp; public A(IRepository aRepository, IRepository bRepository, IRepository bRepository)&nbsp; {&nbsp; &nbsp; _aRepository = aRepository;&nbsp; &nbsp; _bRepository = bRepository;&nbsp; &nbsp; _cRepository = cRepository;&nbsp; &nbsp; &nbsp;MethodB();&nbsp; }&nbsp; public IList<int> GetA()&nbsp; {&nbsp; &nbsp; &nbsp; return _aRepository.Get();&nbsp; }&nbsp;&nbsp; public IList<int> GetB()&nbsp; {&nbsp; &nbsp; &nbsp; return _bRepository.Get();&nbsp; }&nbsp;&nbsp; public IList<int> GetC()&nbsp; {&nbsp; &nbsp; &nbsp; return _cRepository.Get();&nbsp; }&nbsp;&nbsp; private void MethodB()&nbsp; {&nbsp; &nbsp; &nbsp; _aRepository.Init();&nbsp; &nbsp; &nbsp; _bRepository.Init();&nbsp; &nbsp; &nbsp; _cRepository.Init();&nbsp; }&nbsp; public bool MethodA(customerCollection foo){...whatever...}}然后在单元测试中,您可以模拟您的存储库并利用 Moq 库Mock<IRepository> aRepositoryMock = new Mock<IRepository>();Mock<IRepository> bRepositoryMock = new Mock<IRepository>();Mock<IRepository> cRepositoryMock = new Mock<IRepository>();aRepositoryMock.Setup(m => m.Init)...setup Callback for exampleaRepositoryMock.Setup(m => m.Get()).Returns(...some list...)...aslo you can setup b and c repositories...var sut = new A(aRepositoryMock.Object, bRepositoryMock.Object, cRepositoryMock.Object);
打开App,查看更多内容
随时随地看视频慕课网APP