I have an interface which is implemented by two classes.
public IMyInterface
{
void DoSomething();
}
public abstract class MyBaseClass
{
internal readonly SomeParameter p;
public MyBaseClass (SomeParameter p)
{
this.p = p;
}
}
public class Foo : MyBaseClass, IMyInterface
{
public Foo (SomeParameter p) : base(SomeParameter p)
{
}
}
public class Bar : MyBaseClass, IMyInterface
{
public Bar (SomeParameter p) : base(SomeParameter p)
{
}
}
Now how should I test DoSomething()
method implemented in Foo
class using Moq?
@Nkosi I want to do something like following.
public class FooTest
{
[Fact]
public void DoSomethingTest()
{
//Arrange
//Here I'm facing problem to get a mock for Foo class.
//Mock of IMyInterface must be Foo here.
var foo = new Mock<IMyInterface>();
//Act
//Another problem: Here DoSomething is not getting called.
foo.DoSomething();
//Assert
}
}
CodePudding user response:
It seems you are confused as to what the mock objects are meant to do. You do not mock the class you are testing. Mocks are meant to replace dependencies for the classes you test (Like the p
constructor parameter in your example). To test the class you instantiate the actual class you want to test, so:
public class FooTest
{
[Fact]
public void DoSomethingTest()
{
//Arrange
var p = new Mock<SomeParameter>();
var foo = new Foo(p.Object);
//Act
foo.DoSomething();
//Assert
}
}