我想为我的控制器创建一个Spring Boot测试,但是我不知道如何。
这是我的代码:
控制器:
@PostMapping(value = Constants.LOGOUT_URL)
public String logout (HttpServletRequest request) throws ApiException {
String authHeader = request.getHeader("Authorization");
if (authHeader != null) {
try {
String tokenValue = authHeader.replace("Bearer", "").trim();
OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
tokenStore.removeAccessToken(accessToken);
} catch (Exception e) {
return HttpStatus.NOT_FOUND.toString();
}
}
return Utils.convertDateTime();
}
这是我的测试,这使我产生了NullPointerException:
@RunWith(SpringJUnit4ClassRunner.class)
@AutoConfigureRestDocs
public class AuthControllerTest {
@Rule
public JUnitRestDocumentation jUnitRestDocumentation = new JUnitRestDocumentation();
@InjectMocks
private AuthController controller = new AuthController();
// To be initialised in the setup method.
private MockMvc mockMvc;
@Mock
private AuthService service;
@Before
public void setup() {
mockMvc = MockMvcBuilders.standaloneSetup(controller)
.apply(documentationConfiguration(this.jUnitRestDocumentation))
.build();
}
@Test
public void getLogout() throws Exception, ApiException {
String result = "{\"date\":\"20190212:0000\"}";
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
when(request.getHeader("principal")).thenReturn("admin");
when(request.getHeader("authorization")).thenReturn("authtoken");
when(controller.logout(any(request.getClass()))).thenReturn(result);
}
}
我不知道如何对注销控制器进行测试
我得到的异常如下:
java.lang.NullPointerException: null
at com.sodexo.oneapp.api.auth.AuthController.login(AuthController.java:35)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
答案 0 :(得分:0)
您可以使用Rest Assured轻松测试Controller。这是文档:https://github.com/rest-assured/rest-assured/wiki/Usage
测试可能看起来像这样:
@RunWith(MockitoJUnitRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
class MyControllerTest {
@Mock
private MyService myService;
@InjectMocks
private MyController MyController;
@Before
public static void init(){
RestAssured.baseURI = "http://localhost";
RestAssured.port = 8080;
}
@Test
void givenUrl_whenSuccessOnGetLogoutAndStuff_thenCorrect() {
when(this.myService.getLogout(stuff)).thenReturn(something);
given()
.standaloneSetup(new MyController(this.myService))
.header("principal", "admin")
.header("authorization", "authtoken")
.when()
.get("/logout")
.then()
.statusCode(200)
.statusLine("...")
.body(something);
}
}
确保使用“放心的人”的MockMvc模块:
import static io.restassured.module.mockmvc.RestAssuredMockMvc.*;