使用easymock / powermock模拟超级方法调用

时间:2018-07-01 08:37:14

标签: spring powermock easymock

我将easymock与Spring项目集成在一起,并执行了大多数单元测试。但是遇到了无法模拟超级方法的问题。当我运行测试类时,它说不支持方法。

任何想法都出了什么问题,因为最近几天我都在尽力而为,却无法获得有关如何模拟超级方法的任何线索。

public function store(Request $request)
{
    $post = new Post;
    $post->title= $request->input('title');//change
    $post->save();
}

要测试的类:

org.springframework.security.authentication.AuthenticationServiceException: Authentication method not supported: 
    at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:71)
    at com.dashboard.core.CustomAuthenticationFilter.attemptAuthentication(CustomAuthenticationFilter.java:20)
    at com.dashboard.core.CustomAuthenticationFilterTest.testAttemptAuthentication(CustomAuthenticationFilterTest.java:64)

我的测试班:

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.dashboard.domain.ApplicationConstant;

public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response){
        String username = request.getParameter("j_username");
        String password = request.getParameter("j_password");
        if(isValidUsername(username) && isValidPassword(password) ){
            return super.attemptAuthentication(request, response);
        }
        throw new BadCredentialsException(ApplicationConstant.CREDENTIALS_NOT_FORMAT.getValue());
    }

    private static boolean isValidUsername(String username){
        return !StringUtils.isEmpty(username) && username.matches(ApplicationConstant.USERNAME_PATTERN.getValue());
    }

    private static boolean isValidPassword(String password){
        return !StringUtils.isEmpty(password) && password.matches(ApplicationConstant.PWD_PATTERN.getValue());
    }
}

1 个答案:

答案 0 :(得分:0)

UsernamePasswordAuthenticationFilter是基类,而不是注入的依赖项。通常,您可以使用partial mock解决此问题。但是您不能这样做,因为CustomAuthenticationFilter正在调用super.attemptAuthentication,这无法被嘲笑。

您的解决方案是:

  1. 测试CustomAuthenticationFilter及其超类
  2. 改为使用委派模式

但是由于当前Spring对于此类过滤器的设计,委托似乎很笨拙。因此,总的来说,测试是您最好的选择。