0
我正在使用spring引導開發一個應用程序。我想單元測試我的Rest服務登錄(),我的服務運行良好(我使用郵差)。請看看我爲聯合測試所做的嘗試。 例如當我輸入正確的用戶名和密碼,我得到了一個標記爲一返回值:如何使用spring引導爲REST登錄Web服務編寫單元測試
,當我輸入一個錯誤的用戶名和密碼,我得到這個:
這些是我的應用程序的體系結構:
app
|
src/main/java
|--DemoApplication.java
|--dao.package
|--UserRepository.java
|--jwt.package
|--UserController.java
src/test/java
|--jwt.package.test
|--UserControllerTest.java
DemoApplication.java
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
}
}
UserController.java
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserRepository userRepository;
@PostMapping("login")
public LoginResponse login(@RequestBody final UserLogin login)
throws ServletException,
UnsupportedEncodingException {
User user = userRepository.findByUsernameAndPassword(login.username,
login.password);
if (user == null)
throw new ServletException("Invalid login");
StringBuilder roles = new StringBuilder();
user.getRoles()
.forEach(role -> roles.append(role.getName()).append(","));
return new LoginResponse(Jwts.builder().setSubject(login.username)
.claim("roles", roles).setIssuedAt(new Date())
.signWith(SignatureAlgorithm.HS256, "accenture".getBytes("UTF-8"))
.compact());
}
private static class UserLogin {
public String username;
public String password;
}
private static class LoginResponse {
public String token;
public LoginResponse(final String token) {
this.token = token;
}
}
}
我想測試我的登錄Web服務,但仍然不正確。任何人都可以幫我請進行單元測試我的登錄服務
UserControllerTest.java:所有的
@RunWith(SpringRunner.class)
@WebMvcTest(value = UserController.class, secure = false)
public class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private UserRepository userRepository;
User mockUser = new User("test", "test");
String exampleUserJson = "{\"username\":\"toto\",\"password\":\"toto\"}";
@Test
public void loginTest() throws Exception {
User mockUser = new User("test", "test");
Mockito.when(
userRepository.findByUsernameAndPassword(Mockito.anyString(),
Mockito.anyString())).thenReturn(mockUser);
// Send course as body to /students/Student1/courses
RequestBuilder requestBuilder = MockMvcRequestBuilders
.post("/user/login")
.accept(MediaType.APPLICATION_JSON).content(exampleUserJson)
.contentType(MediaType.APPLICATION_JSON);
MvcResult result = mockMvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = result.getResponse();
assertEquals(HttpStatus.INTERNAL_SERVER_ERROR.value(), response.getStatus());
assertEquals("http://localhost/user/login",
response.getHeader(HttpHeaders.LOCATION));
}