我想为我的控制器创建一个弹簧启动测试,但我不知道如何。
这是我的代码:
控制器:
@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)
您可以放心地使用REST来测试控制器非常容易。这是文档:https://github.com/rest-assure/rest-ashure/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.*;