简体   繁体   中英

How to set mock object in proxy-based Spring bean?

I'm having problems trying to set the mock object in my wired bean in my testcase.

Here's my simplified problem:-

class SomeClassTest {
    @Autowired
    private SomeClass   someClass;

    @Test
    public void testRun() {
        Service service = mock(ServiceImpl.class);
        when(service.doIt()).thenReturn("");

        // this line fails with ClassCastException
        ((SomeClassImpl) someClass).setService(service);

        assertEquals("bad", someClass.run());
    }
}

interface SomeClass {
    String run();
}

class SomeClassImpl implements SomeClass {
    private Service service;

    public void setService(Service service) {
        this.service = service;
    }

    public String run() {
        String value = service.doIt();
        return StringUtils.isBlank(value) ? "bad" : "good";
    }
}

interface Service {
    String doIt();
}

class ServiceImpl implements Service {
    public String doIt() {
        return "bla";
    }
}

In this example, I'm trying to test SomeClass by mocking out Service.doIt() so that I can test different conditions. The problem I'm facing is I'm not sure how exactly I should set the mock Service object in SomeClass . The only way I can think of is to downcast SomeClass into the concrete class to call setService(...) , however, I'm getting a ClassCastException saying $Proxy incompatible with SomeClassImpl . I believe all my bean wirings are proxy-based because I'm using AOP to configure the transaction. I really do not want to expose setService(...) in SomeClass interface because it makes no sense to do so in my production code.

Is there a way for me to accomplish this?

Thanks.

You can use the @Resource annotation to get the implementation :

@Resource
private SomeClassImpl someClass;
...
someClass.setService(service);
...
  1. Use additional interface for Service setter than. or
  2. Do not autowire Service but use 'new' operator in your test.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM