2016-08-23 81 views
3

我們有一個Spring Boot 1.4 Web應用程序公開了一個REST API,我們希望運行一些集成測試。401中的Spring Boot集成測試結果

在我們的測試中,我們得到Spring Boot在本地啓動web應用程序,然後我們對api進行一些調用。

如果我們簡單地運行web應用程序本身並擊中端點,我們會得到200/OK響應,這是預期的。運行測試,但是,我們得到一個401/Unauthorized服務器響應。

我在哪裏查看可能導致授權錯誤的原因?

@RunWith(SpringRunner.class) 
@SpringBootTest(classes = {Application.class}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) 
public class DemoApplication3IT { 
    private final Logger log = LoggerFactory.getLogger(DemoApplication3IT.class); 

    @Autowired 
    private TestRestTemplate restTemplate; 

    @Test 
    public void getFunky() throws IOException { 
     ResponseEntity<String> response = 
      this.restTemplate.getForEntity("http://localhost:8080/api/funky", String.class); 
     log.info("TestRestTemplate response Code: " + response.getStatusCode()); 
     assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); // Expected :200, Actual :401 
    } 
} 

奇怪的是,用瀏覽器擊中端點可以正常工作,但集成測試失敗。

+0

你能否包含定義安全性的'Application.class'的配置?某事正在保護端點並導致401被返回。 –

+0

這是一個大型的專有應用程序,所以共享是有問題的。 :(有沒有我們尋找的典型豆類?我可能可以淨化它們並分享。 – Bex

回答

1

最終,問題在於單元測試環境中已禁用安全性而不是。溶液中加入以下行application.yml

management.security.enabled: false 
management.health.db.enabled: false 
security.basic.enabled: false 
0

您也可以在您的測試類中添加像這樣保存複製application.properties:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, 
     classes = { TestDataSourceConfig.class }, 
     properties = { 
       "security.basic.enabled=false" 
     }) 

應該也被關閉這個註解:

@AutoConfigureMockMvc(secure = false) 

,但目前我無法得到那個工作(也許有會在未來的答案:Spring Boot integration test ignoring secure=false in AutoConfigureMockMvc annotation, get 401

相關問題