如何对OAUTH Spring Boot进行模拟测试

时间:2019-02-21 14:41:58

标签: java spring-boot mockito

我想用Mock for Spring Boot做一个测试用例,但是我无法连接到授权服务器:

我的控制器:

public class AuthController {

@Autowired
private AuthService authService;

@Autowired
private TokenStore tokenStore;

@PostMapping(value = Constants.LOGIN_URL,
        consumes = MediaType.APPLICATION_JSON_VALUE,
        produces = MediaType.APPLICATION_JSON_VALUE)
public Auth login(@RequestBody Auth login, OAuth2Authentication auth) throws ApiException {

    Auth result = authService.auth(login);

    final OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) auth.getDetails();
    result.setAccessToken(details.getTokenValue());
    final OAuth2AccessToken accessToken = tokenStore.readAccessToken(details.getTokenValue());
    result.setTtl(accessToken.getExpiresIn());

    return result;
}

这是我的测试,但是会出现一个NullPointer错误,可能是因为该方法中有一个参数(OAuth2Authentication auth),我不知道如何将其放入测试中:

@Before
public void setup() {
    mockMvc = MockMvcBuilders.standaloneSetup(controller)                
          .apply(documentationConfiguration(this.jUnitRestDocumentation))
          .setCustomArgumentResolvers(new AuthenticationPrincipalArgumentResolver()).build();
}

@Test
public void getLogin() throws Exception, ApiException {

   Auth authMock = Mockito.mock(Auth.class);
   Mockito.when(service.auth(Mockito.any(Auth.class))).thenReturn(authMock);

    String requestBody = "{" +
            "\"username\":" + "\"YENNIFER\"" +
            ",\"nid\":" + "\"13991676\"" +
            ",\"password\":" + "\"password\"" +
            ",\"email\":" + "\"cervecera.artesanal@gmail.com\"" +
            "}";

    mockMvc.perform(MockMvcRequestBuilders.post("/api/v1/auth/login")
            .contentType(MediaType.APPLICATION_JSON)
            .content(requestBody))
            .andExpect(status().isOk());
}

1 个答案:

答案 0 :(得分:0)

您可以简单地模拟AuthService并将其注入控制器,例如:

@RunWith(SpringJUnit4ClassRunner.class)
public class AuthControllerTest {

    @Mock
    private AuthService authService;

    @InjectMocks
    private AuthController controller;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testAuth() {
        Auth authMock = Mockito.mock(Auth.class);
        Mockito.when(authService.auth(Mockito.any(Auth.class)).thenReturn(auth));
    }
}