开发者

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

开发者 https://www.devze.com 2023-02-22 08:36 出处:网络
I\'m having problems trying to set the mock object in my wired bean in my testcase. Here\'s my simplified problem:-

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 doI开发者_如何学运维t() {
        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.
0

精彩评论

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

关注公众号