3

I'm trying to write a unit test for a class but the class has a Private variable initiated when the class is created..

public class OrderFormService : IOrderFormService
{
    private readonly IOrderItems _orderItems;
    private readonly string _orderStartingGroup;

    // constructor
    public OrderFormService(IOrderItems orderItems)
    {
        _orderItems = orderItems;
        _orderStartingGroup = "Sales";
    {

    // Other Methods

}

I'm trying to write a unit test now and to test a method in this class and it utilises the variable _orderStartingGroup...

[TestFixture]
public class OrderFormServiceTests
{
    private ITreatmentFormService _service;
    private Mock<IOrderItems> _orderItems;

    [SetUp]
    public void SetUp()
    {
        _orderItems = new Mock<IOrderItems>();
        _service = new OrderFormService(_orderItems);
    }
}

Is it possible to set up the _orderStartingGroup in OrderFormServiceTest so it can be used in unit tests for testing some methods in OrderFormService? If so, how do I go about it? I've tried googling it but results keep talking about accessing private variables in the class you're testing but this isn't what I'm trying to do.

Thanks in advance :)

CodeLearner
  • 389
  • 2
  • 6
  • 14

2 Answers2

2

Well even if there is a way of setting private field directly from unit test method it’ll break an architectural principle or two..

There are a few ways of how to deal with this problem. The simplest solution would be to change the ctor signature by adding an optional parameter:

// constructor
public OrderFormService(IOrderItems orderItems, string orderStartingGroup = null)
{
    _orderItems = orderItems;
    _orderStartingGroup = orderStartingGroup ?? "Sales";
{

And use it in unit test:

[SetUp]
public void SetUp()
{
    _orderItems = new Mock<IOrderItems>();
    _service = new OrderFormService(_orderItems, “testValue”);
}
Fabjan
  • 13,506
  • 4
  • 25
  • 52
1

I think this might an indicator that you are doing something wrong. I would rather focus on public interfaces rather than testing internal implementation. If this somehow reflected in public interface there should be a way to set it via public interface or convention (say read from a config file).

But if you absolutely need to do that, you can consider following:

  1. Use fabjan's answer

  2. Set private field value with reflection

  3. Make this private member as protected and create an derived test class.

Felix
  • 830
  • 10
  • 17