5

My java project has multiple layers such as Controller (depends on) Service (depends on) DAO. My goal is to unit test Controller.

I created Mock service object to inject it in to Controller class.

After googling , Ive learnt that I could use java interface to do so.

Ideally, service layer does not need an interface.

I wonder if there is a different approach to inject mock object without a java interface.

2 Answers 2

6

There are mocking libraries like Mockito, which could create mocks for classes without the need of interfaces.

MyService serviceMock = org.Mockito.mock(MyService.class);
controller.setService(serviceMock);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks @StefanBirkner. Problem solved. FYI : you need to pass MyService.class in mock(..) . BTWN Ive used @RunWith(MockitoJUnitRunner.class) to initialze mock objects.. code is much cleaner.
With it's clean api and features like this it baffles me that Mockito isn't the de facto standard for mocking in java.
1

If a class in controller uses a service class, you can mock the service class an inject into the controller class when you are unit testing the controller class.

public class MyController {
    private MyService myService;

    public void setMyService(MyService myService) {
        this.myservice = myservice;
    }
}

Whether you mock an interface or a class depends on the reference type that the controller class has.

In above example, if MyService is an interface you can mock that interface. But if it is a class, then you have to mock that class.

Hope that resolves your concern.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.