如何对创建另一个类的新实例的方法或构造函数进行单元测试 [英] How to unit test a method or constructor which creates a new instance of another class

查看:62
本文介绍了如何对创建另一个类的新实例的方法或构造函数进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经对该主题进行了广泛的研究,但是还没有找到可靠的答案.

I've done extensive research on this topic and have yet to find a reliable answer so here goes.

我有一个要测试的构造函数.此构造函数初始化另一个类,以设置一个全局变量,该变量在该类的其余部分中都是必需的.但是,构造函数初始化的类的构造函数与诸如Web会话之类的东西和其他已设置的变量具有依赖性,而这些变量在运行任何测试时都不会设置.我该如何适当地模拟它以确保我只是在测试构造函数?

I have a constructor I'd like to test. This constructor initializes another class in order to set a global variable which is necessary throughout the rest of the class. However, the constructor of the class which the constructor initializes has dependencies on things like web session and other variables being set which are not set when the any tests run. How can I properly mock this to make sure I'm just testing the constructor?

这是要测试的构造函数:

Here's the constructor to be tested:

public CheckoutManager()
{
    _orderController = new OrderController();
    _orderController.PropertyChanged += (sender, args) => NotifyPropertyChanged(args.PropertyName);
}

问题出在OrderController构造函数中:

The problem lies in the OrderController constructor:

public OrderController()
{
    _customer = WebUserSession.Current.Profile.Customer;
    _srd = ContextManager.GetStandardRequestByCulture( CultureInfo.CurrentUICulture.Name );
    WarehouseData data = new WarehouseData();
    data.WarehouseID = 0;   // TODO: Convert the 0 warehouse to a web warehouse type

    // Grab the attention items from the session
    AttentionItems = WebUserSession.Current.OrderAttentionItems;

    // Load the shopping cart
    _cart = ShoppingCartManager.Cart;
}

这是我尝试过的测试:

[TestMethod]
public void Constructor_ExpectInstantiation()
{
    var checkoutManager = new CheckoutManager();

    Assert.IsNotNull( checkoutManager );
}

它在_customer = WebUserSession.Current.Profile.Customer轰炸;线.您如何使用Moq来模拟呢?如果不能嘲笑,为什么有很好的解释?如何将原始构造函数修改为具有可测试性的相同功能?预先谢谢你.

It bombs out at the _customer = WebUserSession.Current.Profile.Customer; line. How do you mock this using Moq? If it cannot be mocked, is there a good explanation as to why? How could the original constructor be modified to have the same functionality in a more testable way? Thank you in advance.

推荐答案

您将无法对该代码使用Moq测试.你可以

You won't be able to use Moq test to this code. You could

  • 通过添加接受OrderController的构造函数来修改代码,使其更具可测试性
  • 使用更高级的测试技术,例如 查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆