Question

I write controller tests for Spring with Jmock. The controllers use interfaces for database operations. These are service classes. I can jmock them and pass them to controller in test via setter.

Real controller has a service marked with @Reource-anotation

@Resource private Service service;

Test final Service service = context.mock(Service.class); controller.setService(service); controller.CallMethodToTest();

In controller code service object is usually intialized with Spring's @Resource anotation.The problem is when the controller uses same services in some inner call, for example validator or inner class.

Real validator also has a service marked with @Reource-anotation

@Resource private Service service;

In test I can e.g introduce validator object, set service on it and pass it to controller.

 MyValidator validator = new MyValidator();
 validator.setService(service);
 controller.setValidator(validator);

Let's say validator. validate calls service.getSomething. I'd needed to write Expectations for getSomething(); In controller the same method can be called too.

        context.checking(new Expectations() {
        {
            allowing(service).getSomething();
            will(returnValue(mockData));

        }
    });

Despite of the allowing-cardinality, situation like this causes

 allowed, already invoked 1 time

This is a common scenario and I can't provide more specific code. I guess this has something to do with both controller and validator service method calls. Can anyone give me a hint on fixing this?

Was it helpful?

Solution

If you use JMock, then every mock object has a name. This name must be unique.

If you use the method Mockery.mock(Class<T> typeToMock) then the name will be derived from the class name. So you can create only one mock of each class with this method.

If you need several different mocks of the same class, then use Mockery.mock(Class<T> typeToMock, String name) instead, and give each mock an different name.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top