繁体   English   中英

单元测试Spring抛出BeanNotOfRequiredTypeException

[英]Unit testing Spring throws BeanNotOfRequiredTypeException

运行测试类将引发以下异常:

BeanNotOfRequiredTypeException: Bean named 'myServiceImpl' is expected to be of type 'MyServiceImpl' but was actually of type 'com.sun.proxy.$Proxy139'

该错误仅在单元测试中引发,程序本身可以工作。

我的介面

public interface MyService {

    public String testMethod();

}

我的实施

@Service
public class MyServiceImpl implements MyService{

    @Autowired
    private TransactionRepository transactionRepo;

    @Autowired
    private AccountRepository accountRepository;

    @Autowired
    private BankAccountStatementFactory baStatementFactory;

    public String myMethod() {
        return "Run My Method";
    }

}

我的单元测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class DeleteMeTest{


    @Mock
    private TransactionRepository transactionRepo;

    @Mock
    private AccountRepository accountRepository;

    @Mock
    private BankAccountStatementFactory baStatementFactory;

    @InjectMocks
    @Resource
    MyServiceImpl myService;


    @org.junit.Before
    public void setUp() throws Exception {
        // Initialize mocks created above
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void test() {
        myService.myMethod();
        System.out.println("My Unit Test");
    }

}

运行此测试类将引发以下异常:

BeanNotOfRequiredTypeException: Bean named 'myServiceImpl' is expected to be of type 'MyServiceImpl' but was actually of type 'com.sun.proxy.$Proxy139'

这里的解决方案是将接口而不是实现注入单元测试中,但这将不允许我注入模拟。

那是因为@InjectMocks批注需要实现。 当我尝试将模拟注入接口时,出现以下异常:

Cannot instantiate @InjectMocks field named 'myService'! Cause: the type 'MyService' is an interface.

需要明确的是,所有这些工作在一开始都是有效的,一旦我重新包装了课程,它们就会变得很糟糕。 这可能是原因,但不是100%确定。

关于什么可能导致此BeanNotOfRequiredTypeException任何提示?

谢谢!

由于这是一个单元测试,因此您不需要Spring IMHO。

只需以这种方式初始化测试的类:

@InjectMocks
MyServiceImpl myService = new MyServiceImpl();

您还可以删除以下注释:

@RunWith(SpringRunner.class)
@SpringBootTest

如果您确实需要使用Spring (在您的文章中尚不清楚在单元测试中使用Spring的原因),则可以尝试取消代理bean:

为代理和bean分别声明:

@Resource
MyServiceImpl proxy;

@InjectMocks
MyServiceImpl myService;

然后在setUp()初始化它们:

@org.junit.Before
public void setUp() throws Exception {
    // Initialize mocks created above
    myService = (MyServiceImpl)((TargetSource) proxy).getTarget();
    MockitoAnnotations.initMocks(this);

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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