JMockit是常用的单测编写的框架,可注入成员变量和实现,但是最近在使用@Injectable
注入Spring中@Resource
注解的成员变量时,发现无法生效,接下来说下解决办法。
首先我们看看以下出问题的示例,业务代码如下:
public class BusinessCode { @Resource(name = "businessServiceImpl") private BusinessService businessService; public void execute() { } }
这个是最初写的单测类,代码如下:
import mockit.Injectable; import mockit.Tested; import org.junit.Test; public class BusinessCodeTest { @Tested BusinessCode businessCode; @Injectable private BusinessService businessService; @Test public void test() { businessCode.execute(); } }
执行单元测试后,会报这个错:
java.lang.IllegalStateException: Missing @Injectable for field "BusinessService businessService" in BusinessCode
我当时也奇怪了,@Autowired
的都是这么用的,都没问题,最后发现,对于@Resource
因为Spring会根据name找注入类,所以变量名应该也要改为name的名字,就好了,改完后的代码如下:
public class BusinessCodeTest { @Tested BusinessCode businessCode; @Injectable private BusinessService businessServiceImpl; @Test public void test() { businessCode.execute(); } }
至此,问题解决,重点在于变量名要和name相同,特此记录下。