Check if a method in ClassA is called from another method in ClassA

You can check if a method using Moq and dependency injection has been called. However, is it possible to verify that one method in a class calls another in the same class?

For example, I want to verify that if I register an exception, an informational message is also logged.

Method:

public void Error(string message, Exception exception, long logId = 0) { var int32 = (int)logId; Info("Id was converted to an int so that it would fit in the log: " + logId, int32); Error(message, exception, int32); } 

It was my attempt at testing the module. The test fails, is there a way that this can be done?

 void logging_an_error_with_a_long_id_also_logs_info() { var mock = new Mock<ILogger>(); var testedClass = new Logger(); var counter = 0; testedClass.Error("test" + counter++, new Exception("test" + counter), Int64.MaxValue); mock.Verify(m => m.Info(It.IsAny<string>(), It.IsAny<int>())); } 

Since the Info and Error methods are in the same class (ClassA), I do not believe that I can pass ClassA as a dependency on ClassA. So it does not need to be checked?

+6
source share
2 answers

The best you can do is make Info virtual . This will allow you to create a Mock<Logger> , set CallBase = true and make sure Info been called.

 var mock = new Mock<Logger> { CallBase = true }; mock.Object.Error("test" + counter++, new Exception("test" + counter), Int64.MaxValue); mock.Verify(m => m.Info(It.IsAny<string>(), It.IsAny<int>())); 

That way, you are still calling the actual implementation of Error , but you used Moq to test the Info method.

+7
source

It looks like you are trying to verify the wrong thing. It doesn’t matter that the Info method for your class is called from the Error method, which is important when the Info method behaves. How this happens is a detail of class implementation.

If I had a math class with two functions:

 public int Mult(int x, int y) { return x*y; } public int Sqr(int x) { return Mult(x,y); } 

I would not test the Sqr call called by the Mult function, I would check Sqr(4)==16 . It does not matter if this calculation is performed in the Sqr method or in another class method.

While the @Andrew solution is probably what you need, taunting the class you are testing leads to tightly coupled, fragile trials.

If it is not practical to test the call by observing its side effects, then this may be a sign that the implementation may use a bit of refactoring.

+5
source

Source: https://habr.com/ru/post/990017/


All Articles