2016-08-05 108 views
0

我有一個簡單的彈簧啓動(1.3.5)應用程序,它有一個簡單的集成測試,直到我引入spring-boot-starter-security。我已經在application.properties中設置了security.user.name和security.user.password,這似乎需要密碼保護我的端點(並且如果可能的話,我不會通過添加不必要的角色或安全配置來使事情複雜化)。但是現在集成測試失敗了。我的測試類:如何使用基本身份驗證集成測試Spring Boot?

@RunWith(SpringJUnit4ClassRunner.class) 
@SpringApplicationConfiguration(classes = Application.class) 
@WebIntegrationTest(randomPort = true) 
public class MyTestsIT { 

    private TestRestTemplate template = new TestRestTemplate(); 
    private URL base; 

    @Value("${security.user.name}") 
    private String username; 

    @Value("${security.user.password}") 
    private String password; 

    @Value("${local.server.port}") 
    private int port; 

    @Before 
    public void beforeTest() throws MalformedURLException { 
     base = new URL("http://" + username + ":" + password + "@localhost:" + port); 
    } 

    @Test 
    public void testHello() throws IllegalStateException, IOException { 
     System.err.println(base.toString() + "/hello"); 
     ResponseEntity<String> response = template.getForEntity(base.toString() + "/hello", String.class); 
     assertEquals("Incorrect HTTP status returned", HttpStatus.OK, response.getStatusCode()); 
     String body = response.getBody(); 
     assertEquals("Incorrect response string.", "Hello World!", body); 
    } 
} 

的println語句,顯示正確的網址,同一個我已經能夠在捲曲使用,當我運行的應用程序:

捲曲http://user:[email protected]:8181/hello

斷言爲返回狀態401失敗,我做錯了什麼?

回答

1

D'oh!只要我發佈我的問題,我在Basic authentication for REST API using spring restTemplate找到答案。不知道爲什麼我的搜索沒有打到它。對不起,我希望這會幫助別人。

@Before 
public void beforeTest() throws MalformedURLException { 
    template = new TestRestTemplate(username, password); 
    base = new URL("http://localhost:" + port); 
} 
相關問題