Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set up Private variable in Class for Nunit Test

Tags:

c#

nunit

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 :)

like image 813
CodeLearner Avatar asked Nov 19 '25 10:11

CodeLearner


1 Answers

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”);
}
like image 97
Fabjan Avatar answered Nov 20 '25 22:11

Fabjan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!