我必须对Processor类中的SubmitApplication方法进行单元测试。
方法SubmitApplication上的@PreValidate(actionName =“ PRE_VALIDATE”)与Aspect(PreValidateAspect)关联,这称为 自动,因为我确实测试了该方法。我不希望调用此Aspect,因为我只想测试函数内部的行。
使用的版本:春季版(4.3.16),mockito-core(2.8.47),powermock-api-mockito(2-1.7.0)
请让我知道如何在单元测试功能时禁用/取消此方面代码的运行。
public class ProcessorTest {
@InjectMocks
private Processor processor;
@Test
public void testSubmitApplication() {
processor.submitApplication();
}
}
public class Processor {
@PreValidate(actionName="PRE_VALIDATE")
public void submitApplication(){
Long startTime = System.currentTimeMillis();
}
}
@Aspect
@Component
@Configurable
public class PreValidateAspect {
@Around("execution(* *(..)) && " +
"(@annotation(com.PreValidate) " +
"|| @within(com.PreValidate) )")
public Object validate(ProceedingJoinPoint joinPoint) throws Throwable{
}
}
答案 0 :(得分:0)
一种方法是按照coder的建议去。
但是这种方法对我不起作用。如评论中所述。方面不能被嘲笑。相反,您可以执行此操作。
@Aspect
@Component
@Configurable
public class PreValidateAspect {
@Autowired
Utils utils;
@Around("execution(* *(..)) && " +
"(@annotation(com.PreValidate) " +
"|| @within(com.PreValidate) )")
public Object validate(ProceedingJoinPoint joinPoint) throws Throwable{
if(utils.aspectUtil()) {
return joinPoint.proceed();
}
//else statement
}
}
public class Utils{
public Object aspectUtil() {
//your business logic here
if(validate()){
return true;
}
return false;
}
}
public class ProcessorTest {
@InjectMocks
private Processor processor;
@MockBean
Utils utils;
@Test
public void testSubmitApplication() {
when(utils.validateUtil()).thenReturn(true);
processor.submitApplication();
}
}
通过这种方式,将您的业务逻辑从方面转移到类,并模拟该类以返回true;
答案 1 :(得分:-1)
一种选择是将@ActiveProfiles与@Profile一起使用
@ActiveProfiles("test")
public class ProcessorTest {
@InjectMocks
private Processor processor;
@Test
public void testSubmitApplication() {
processor.submitApplication();
}
}
public class Processor {
@PreValidate(actionName="PRE_VALIDATE")
public void submitApplication(){
Long startTime = System.currentTimeMillis();
}
}
@Aspect
@Component
@Configurable
@Profile("!test")
public class PreValidateAspect {
@Around("execution(* *(..)) && " +
"(@annotation(com.PreValidate) " +
"|| @within(com.PreValidate) )")
public Object validate(ProceedingJoinPoint joinPoint) throws Throwable{
}
}