2017-06-05 90 views
0

我正在使用spring引導開發一個應用程序。我想單元測試我的Rest服務登錄(),我的服務運行良好(我使用郵差)。請看看我爲聯合測試所做的嘗試。 例如當我輸入正確的用戶名和密碼,我得到了一個標記爲一返回值:如何使用spring引導爲REST登錄Web服務編寫單元測試

enter image description here

,當我輸入一個錯誤的用戶名和密碼,我得到這個:

enter image description here

這些是我的應用程序的體系結構:

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)); 

    } 

回答

0

先了解春季安全性是如何工作的。

如果你沒有提供任何配置,它會要求爲每一件事認證。

,如果你想測試認證那麼你需要做的僅僅是調用中包含的用戶名和密碼的安全API,

curl -v http://localhost:9090/mynet/ -u admin:admin12344 -c D:\cookies.txt -H "Accept: application/json" 

成功塞納里奧:在上面的例子中,我叫做安全端點得到一個cookie響應與HTTP/1.1 200,如果認證成功,是您可以使用下面進一步的呼叫,

curl -v http://localhost:9090/mynet/customers -b D:\cookies.txt 

失敗場景:我們得到HTTP/1.1 401 JSON

{"timestamp":1496645081468,"status":401,"error":"Unauthorized","message":"No AuthenticationProvider found for org.springframework.security.authentication.UsernamePasswordAuthenticationToken","path":"/mynet/"} 

注:我知道你需要使用Java代碼,而不是捲曲檢查上面的調用。我用這只是爲了解釋概念。

相關問題