0

I am writing test cases using xUnit. I am testing controller. Below is my controller.

public IActionResult UpdateOption([FromBody] OptionsUpdate optionsUpdate)
{
  var updatingUser = userResolver.GetUserNameFromController(this);
  try
  {
    OptionsUpdate optionsUpdateData = DataParser.MakeDateConsistent(optionsUpdate);
    optionService.Update(optionsUpdateData, updatingUser);
    return Ok();
  }
  catch (Exception e)
  {
    log.Error(e, "Failed to update option parameters");
    return BadRequest();
  }
}

Below is my test method.

[Fact]
public void OnSuccess_ShouldBeOk()
{
  controller.GetDependency<IOptionService>()
    .Update(Arg.Any<OptionsUpdate>(), Arg.Any<string>());

  var result = controller.Target.UpdateOption(new OptionsUpdate()) as StatusCodeResult;
  result.StatusCode.ShouldBe(200);
}

In the above code When unit test case is writing below line of code throwing error.

 OptionsUpdate optionsUpdateData = DataParser.MakeDateConsistent(optionsUpdate);

Below is the implementation of MakeDateConsistent

public static OptionsUpdate MakeDateConsistent(OptionsUpdate optionsUpdate)
{
  optionsUpdate.Values[Constants.OptionStoreUpdateKeys.OnRangeDate] = ConvertDDMMYYYYToYYYYMMDD(optionsUpdate.Values[Constants.OptionStoreUpdateKeys.OnRangeDate]);
  if (optionsUpdate.Values.ContainsKey(Constants.OptionStoreUpdateKeys.OffRangeDate))
  {
    if (optionsUpdate.Values[Constants.OptionStoreUpdateKeys.OffRangeDate] != string.Empty)
    {
      optionsUpdate.Values[Constants.OptionStoreUpdateKeys.OffRangeDate] = ConvertDDMMYYYYToYYYYMMDD(optionsUpdate.Values[Constants.OptionStoreUpdateKeys.OffRangeDate]);
    }
  }

  return optionsUpdate;
}

I edited my code as below.

var rawUpdate = new OptionsUpdate()
        {
          Keys = new List<OptionStore>()
        {
          new OptionStore() { Option = optionId, Store = store.ToString() }
        },
          Values = new Dictionary<string, string>()
        {
          { Constants.OptionStoreUpdateKeys.Lspl, lspl.ToString() },
          { Constants.OptionStoreUpdateKeys.OnRangeDate, "01/01/2018" },
        }
        };
        DataParser.MakeDateConsistent(rawUpdate).Returns(rawUpdate);

This is throwing error as

NSubstitute.Exceptions.CouldNotSetReturnDueToTypeMismatchException: 'Can not return value of type OptionsUpdate for IOptionService.Update (expected type Int32).

I dont want to create any interface to test this. Can someone help me to mock MakeDateConsistent static method?

Niranjan
  • 1,881
  • 6
  • 44
  • 71

1 Answers1

1

The question is, why do you need the method to be static? You should not use static methods that talk with other dependencies. They should at most work on their own properties and values. If they do, you do not have to mock them. Use a proper class and inject it for all other dependencies.

andreasnico
  • 1,478
  • 14
  • 23