开发者

Unit Testing using Mockito or JMock

开发者 https://www.devze.com 2023-03-09 01:56 出处:网络
Unit Testing: I have the following classes public class BImpl extends AImpl { public BImpl(final C c) { super(c);

Unit Testing:

I have the following classes

public class BImpl extends AImpl
{
    public BImpl(final C c) 
    {
        super(c);
    }

    public String getInfo()
    {
       final String info = getInformation();
       // Do all my logic here
       return info;
    }
}

public abstract class AImpl
{
    public String getInformation()
    {
    // some logic...returns String.
    }
}

I am trying to unit test the method getInfo() by using any of the mocking methods avail开发者_开发百科able either Mockito or JMock.

for example when using Mockito I am using this way:

final AImpl aImpl = mock(AImpl.class);
when(aImpl.getInformation()).thenReturn("ABC");

Now since I have to create an instance of BImpl the only way I can create is using the constructor available.

final BImpl bImpl = new BImpl (C);
bImpl.getInfo();

when it calls into the getInfo() method and it tries to call getInformation(), it isn't calling the mocked object but calling the actual one.

What is the good way to test this method. Is there any other way I can create an instance of BImpl without going by the constructor that I have given above?

Thanks!!


IMHO it's not a problem with mocking libraries but with your design. You want to test getInfo() method by mocking getInformation() on which it depends. Unit testing a method mocking all its dependencies is a right way to go and all mocking frameworks support it pretty well. So why you experience these problems?

Because you have chosen inheritance where composition was actually needed. You are abusing inheritance to implement uses relationship, whereas it should have been composition. Inheriting from a class just to have a convenient access to its methods is asking for trouble. Think of extending EntityManager by every repository/DAO...

You should refactor your code first so that BImpl has AImpl and the latter one is injected somehow. Then you can let some DI framework to perform the injection in production code (or do it yourself) with real implementation while injecting mock in unit test.

0

精彩评论

暂无评论...
验证码 换一张
取 消