Reputation: 306
In the below code, I have a Class Program which have test() method that I want to test.
It calls class "Iprint" method "printnu()" which again calls class "Inumber" method "returnn()" as shown below:
public class number : Inumber
{
public int returnn()
{
return 10;
}
}
public class print : Iprint
{
public int printnu()
{
Inumber test = new number();
return (test.returnn());
}
}
public class program
{
public int test()
{
Iprint hello = new print();
return (hello.printnu());
}
}
How can I mock "returnn()" method of class number? Is it possible? If not any tips on how to solve this kind of problem!
I have tried
Mock<Inumber> mock = new Mock<Inumber>();
mock.Setup<int>(x => x.returnn()).Returns(15);
Iprint test = new print();
var a = test.printnu();
Assert.AreEqual(a, 15);
the mocking doesn't work and execute its own block and return 10! I have tried setting Returnn() method to virtual and mock it, still it didn't work.
Upvotes: 0
Views: 243
Reputation: 247531
Currently you are manually creating the number
class which is what is tightly coupling the print
You should try to avoid tight coupling. It is seen as a code smell and makes testing code in isolation difficult
Inumber
interface would need to be explicitly injected into print
class
public class print : Iprint
private readonly Inumber number;
public print(Inumber number) {
this.number = number;
}
public int printnu() {
return number.returnn();
}
}
for this to be easier to test in isolation.
//Arrange
var expected = 15
var mock = new Mock<Inumber>();
mock.Setup(x => x.returnn()).Returns(expected);
Iprint test = new print(mock.Object);
//Act
var actual = test.printnu();
//Assert
Assert.AreEqual(expected, actual);
Upvotes: 1