2016-08-05 119 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); 
} 
相关问题