日常工作中,编写单元测试是一件再正常不过的事,但是当代码中出现以下代码又该如何测试!
@Service("demo")
public class DemoServiceImpl {
/**
* 获取当前service代理对象
*
* @return 代理对象
*/
private DemoServiceImpl self() {
return (DemoServiceImpl) AopContext.currentProxy();
}
public Integer testA() {
System.out.println("A");
return self().testB();
}
public Integer testB() {
System.out.println("B");
return 2;
}
}
如果单元测试如下的话!
@Resource
private DemoServiceImpl demo;
@Test
public void test() {
int result = demo.testA();
}
那恭喜你,喜提报错一枚
java.lang.IllegalStateException: Cannot find current proxy: Set 'exposeProxy' property on Advised to 'true' to make it available, and ensure that AopContext.currentProxy() is invoked in the same thread as the AOP invocation context.
那在单元测试中,如何从AopContext中获取代理对象呢,要不,试着mock一个出来?
现在pom.xml文件中加入依赖,版本太低有可能会拿不到代理对象哦~
<!-- mockito -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>3.6.28</version>
<scope>test</scope>
</dependency>
单元测试代码:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoServiceImpl.class)
class DemoServiceImplTest {
@Autowired
private DemoService demoService;
@Mock
private DemoServiceImpl demoServiceMock;
@Mock
private MockedStatic<AopContext> aopContextMockedStatic;
@Test
void testA_success() {
aopContextMockedStatic.when(AopContext::currentProxy).thenReturn(demoServiceMock);
demoService.testA();
}
}
通过Bug执行,发现原本拿不到的代理对象现在mock出来了,搞定~
最后推荐下AI编程助手,可以集成到IDE做辅助,智能建议代码,自动生成单元测试,目前还在尝试中! www.aliyun.com/product/yun…