views:

40

answers:

2

I have the following interface and implementation classes:-

public interface MyService {
    void method1();
}

public interface MyServiceImpl implements MyService {
    public void method1() {
        // ...
    }

    /*protected*/ void method2() {
        // ...
    }
}

MyServiceImpl has some Spring wirings, in another word, both method1() and method2() rely on some beans wired by Spring to do their tasks.

I'm trying to test my testcase to test method2(), which is a protected method. Regardless the arguments whether we should be testing protected/private methods, that's not what I want to address here.

Right now, I'm having trouble trying to get my testcase to work properly so that it wires the beans properly.

I initially have this, but it doesn't work because it doesn't expose method2().

@Autowired
private MyService   myService;

I tried this, and I get org.springframework.beans.factory.NoSuchBeanDefinitionException:-

@Autowired
@Qualifier ("myService")
private MyServiceImpl   myService;

Then ,I tried this, and I get org.springframework.beans.factory.BeanNotOfRequiredTypeException:-

@Resource(name = "myService")
private MyServiceImpl   myService;

The only way I can think of now is to stick with autowire and MyService, and then explicitly cast it to MyServiceImpl before executing method2().

Is there a more elegant way to do so?

Thanks.

A: 

Put the JUnit class that tests MyServiceImpl in the same package as MyServiceImpl. Then you should be able to call method2().

Anyway, for unit tests I think you should be setting manually your dependencies to mock objects (if you rely on Spring, then it is not a "unit test" anymore).

EDIT: Are you applying any aspect to myService (transactionality, scoped bean, etc)? If that is the case, Spring may be instantiating a proxy class that implements MyService and delegates to MyServiceImpl. That would be the reason of the type mismatch. If that is the case, then not even casting to MyServiceImpl would work.

gpeche
The testcase sits in the same package as MyServiceImpl.
limc
Ah ok. I did not see the declared type of my service in the first try, so i supposed that was the reason for `method2()` not being accesible.
gpeche
A: 

You could define an applicationcontext.xml used only for setting up your dependencies for testing. A common practice would be to set up a base test class that has an application context. To do that, you can use the annotation @ContextConfiguration( locations={"location of your applicationcontext"} on your base test class.

Glide