0

I have a class that has an update method. In the update method, I'm checking whether its properties are really changed.

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public void UpdatePerson(Person person)
    {
        if (FirstName == person.FirstName && LastName == person.LastName) return;

        ApplyChanges(person);
    }

    public void ApplyChanges(Person person)
    {
        //....
    }

}

I need to ensure that ApplyChanges method is not called when Person properties are same.

Kate.One
  • 21
  • 3

1 Answers1

0

This is more a copy-paste, but I believe the recommendation from Microsoft applies to your question:

In most cases, there should not be a need to test a private method. Private methods are an implementation detail. You can think of it this way: private methods never exist in isolation. At some point, there is going to be a public facing method that calls the private method as part of its implementation. What you should care about is the end result of the public method that calls into the private one.

I suggest reading the link I provided in full detail.

Having said that, if you really think this private method needs to be tested, then that implies that it should probably be moved to a separate class. However, looking at your example, this does not seem to be the case.

Jesse Good
  • 50,901
  • 14
  • 124
  • 166
  • Thanks for your answer. Mostly I'm interested if I can check a method execution without Moq. Now, I've changed ApplyChanges method to Public. – Kate.One Mar 29 '22 at 20:52
  • @K.Arjevanidze: If your question is "is it possible?" and do not care about best practices, you can use [reflection](https://stackoverflow.com/questions/135443/how-do-i-use-reflection-to-invoke-a-private-method). However, doing that would be ignoring all the advice given from most programmers... Also, looking at your code, I see no reason why `ApplyChanges` should be tested at all. – Jesse Good Mar 29 '22 at 21:01
  • thanks for your answer anyways. – Kate.One Mar 29 '22 at 21:11
  • 1
    Similar question was asked almost simultaneously here.. .https://stackoverflow.com/questions/71652221/how-to-verify-that-a-method-of-a-sut-has-benn-called-- only difference is to verify the method was called instead of not called. – Christopher Hamkins Mar 30 '22 at 10:37