I want to write unit tests for MyClass but its base class is an abstract class.
public class MyClass : AbstractBaseClass
{
}
I want to Mock the AbstractBase class, so that I can skip some of the logic in its constructor when I create the MyClass instance I want to test. Is there anyway I can do this?
//Unit Test
var test = new Mock<IInterface>();
var derivedclass = new DerivedClass(test.Object);
test.Setup(d=>d.MyMethod(It.IsAny<string>()).returns(2);
derivedclass.MyMethod("hello");
// Derived Class
class DerivedClass : AbstractClass{
//constuctor
public DerivedClass(IInterface interface){
_interface = interface;
}
public MyMethod(string str){
return 2;
}
}
//Abstract Class
public abstract class AbstractClass
{
// This method gets called when i create the instance of the derived class in my unit
test..
protected AbstractedClass() : this(new SomeOtherClass()){
DoSomethingElse(); /// I want to skip this method or mock it.
}
}
First, we instantiate the FakeDbArticleMock class and indicate which setup we want to use for this test. Then, it is necessary to instantiate the repository we want to test and inject the mock instance into it. Finally, we call the method we are testing and assert the results.
Mocking abstract class using PowerMockmock() method for mocking the abstract classes. Using PowerMock instead of Mockito. mock() is a better approach as it can have control over the private as well as static methods.
Moq is a mocking framework built to facilitate the testing of components with dependencies. As shown earlier, dealing with dependencies could be cumbersome because it requires the creation of test doubles like fakes. Moq makes the creation of fakes redundant by using dynamically generated types.
You can use Moq to create mock objects that simulate or mimic a real object. Moq can be used to mock both classes and interfaces.
By inheriting from the base class you are extending it. It is more about getting your code into a testable state rather than having Moq work for you.
Or have that logic that you don't want to run be part of a virtual method that you can mock. (like @Ohad Horesh's answer:)
public virtual void DoSomethingElse();
mock.Setup(abs => abs.Foo()); //here the mocked method will be called
// rather than the real one
If these options are not viable then you will either have to test that functionality through the derived class or use another mocking framework such as TypeMock Isolator, Moles or JustMock.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With