![](/img/trans.png)
[英]How to configure field annotated with @Mock in Spring Boot Unit test
[英]How to make a Mock Test for OAUTH Spring Boot
我想用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());
}
您可以簡單地模擬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));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.