Let's say I have a simple class with several functions:
public class MyClass { public int GetTotal(int myValue, string myString) { if (myValue > 10) return GetTotal(myValue); else return GetTotal(myString); } public int GetTotal(int myValue) { return myValue * 25 / 12 + 156; } public int GetTotal(string myString) { return myString.Length * 25 / 48 + 27; } }
I would like to unit test to execute my first function and "make fun" of the rest, int GetTotal(int myValue) and int GetTotal(string myString) , to check only the code inside the main function. I use Moq as a mocking structure. Are there any tricks that would allow me to get the code from the function I want to test and make fun of the internal call for other functions? Or do I need to call a second object like this in order to mock everything?
public class MyCalculator { public int GetTotal(int myValue) { return myValue * 25 / 12 + 156; } public int GetTotal(string myString) { return myString.Length * 25 / 48 + 27; } } public class MyClass { MyCalculator _Calculator; public MyClass(MyCalculator calculator) { _Calculator = calculator; } public int GetTotal(int myValue, string myString) { if (myValue > 10) return _Calculator.GetTotal(myValue); else return _Calculator.GetTotal(myString); } }
I know that the latter is the cleanest way, but I have many functions calling themselves one by one so that there are many classes for writing.
Update
Layout implementation of Thomas answer:
public class MyClass { public int GetTotal(int myValue, string myString) { if (myValue > 10) return GetTotal(myValue); else return GetTotal(myString); } public virtual int GetTotal(int myValue) { return myValue * 25 / 12 + 156; } public virtual int GetTotal(string myString) { return myString.Length * 25 / 48 + 27; } } [TestClass] public class Test { [TestMethod] public void MyClass_GetTotal() { Mock<MyClass> myMockedClass = new Mock<MyClass>() {CallBase = true}; myMockedClass.Setup(x => x.GetTotal(It.IsAny<int>())).Returns(1); myMockedClass.Setup(x => x.GetTotal(It.IsAny<string>())).Returns(2); var actual = myMockedClass.Object.GetTotal(0,string.Empty); Assert.AreEqual(2,actual); } }
Update 2
See Guiche's answer also for a more global view of this "problem."
source share