SoFunction
Updated on 2025-03-08

SpringBoot uses Junit dynamic proxy to implement Mock method

Speaking of Spring Boot unit testing, there are two main mainstream integrations, namelyMockito,Junit,This has its own characteristics. In actual development, the test framework I want should be the integrator of this framework. Need to haveJunitAble to run a certain unit use case, a complete project environment, and requiresMockitoCan inject a certain dependency and specify the return value content. Unfortunately, in reality, these two frameworks cannot run at the same time. Suddenly I thought that the Mock injection function could be implemented through AOP's surround notifications to override a certain method's return value. Now there is a Feign interface AService. In fact, our environment does not have this service at all. Calling this method will definitely report an error. The return value is overwritten by proxy technology, so that the method can be called normally. The specific code is implemented as follows

Feign Code

@FeignClient(name = "application-a")
public interface AFeignService {

    @RequestMapping("/url/path/get")
    Result<Object> get();
}

Test cases

@SpringBootTest
@Slf4j
class AFeignServiceTest {

    @Autowired
    private AFeignService aFeignService;

    @Test
    void get() {
        Result<Object> result = ();
        ((result));
    }
}

There will be an error when executing test cases, and there is a missing proxy method. Add proxy configuration class in test

@Aspect
@Slf4j
public class AspConfig {

    @Pointcut("execution(* com..(..))")
    public void pointcue(){

    }

    @Around("pointcue()")
    public Object overrideReturnValue(ProceedingJoinPoint joinPoint) throws Throwable {
        (" execute .................");
        //(); Do not call the original method        ErpReturnDTO dto = new ErpReturnDTO();
        (200);
        (true);
        ("success");
        (new ArrayList&lt;&gt;());
        Result&lt;ErpReturnDTO&gt; result = (dto);
        return result;
    }

}

Add a section configuration class, which is the code for testing purposes. It cannot be written on the src/code, but uses ImportBeanDefinitionRegistrar to reference it in the test. ImportBeanDefinitionRegistrar: It is an interface provided by Spring. Run developers to add customization and add their own configuration classes. Spring Boot component extension is implemented through this interface.

public class TestAopImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        BeanDefinitionBuilder definitionBuilder = ();
        GenericBeanDefinition definition = (GenericBeanDefinition) ();
        ((), definition);
    }

}

Just introduce proxy configuration in the original unit test

@SpringBootTest
@Slf4j
@Import()
class AFeignServiceTest

Run the test case again, there is no exception, and the return object is successfully printed

{"code":0,"data":{"data":[],"message":"success","status":200,"subMessage":"success","success":true},"msg":"The operation is successful","success":true}

With this proxy configuration, you can proxy overwrite the return value of the dependencies in unit tests in normal development, achieving the return value effect of a certain method of Mock.

This is the end of this article about SpringBoot using Junit dynamic proxy to implement Mock methods. For more related SpringBoot Junit Mock methods, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!