簡體   English   中英

如何使用@WithMockUser並從我的屬性文件中傳遞我的用戶名和密碼?

[英]How can I use @WithMockUser and pass my username and password from my properties file?

我正在編寫一個集成測試,其中應用程序具有應用spring security的基本auth。 我正在使用@WithMockUser告訴mockMVC如何使用我的端點進行身份驗證。

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@WithMockUser(username="username", password="password")

這有效,但我想知道我是否可以用我的application.properties文件中的值引用替換這些字符串類似於你如何做:

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

以上可能嗎?

您只能將常量表達式傳遞給注釋,但另一種方法是創建自己的安全上下文,如@WithSecurityContext章節中所述: https ://docs.spring.io/spring-security/site/docs/5.0.x/ 參考/ HTML /測試method.html

我還將創建自己的測試屬性配置文件,該文件將用於從測試中讀取屬性。

我最終廢棄了@WithMockUser注釋並使用了這個對我的用例更好的解決方案。 此方法使用配置的基本身份驗證進行身份驗證,因此如果要進行更改則不會出現問題。

@RunWith(SpringRunner.class)
@SpringBootTest
public class sampleTestIT {

    @Autowired
    private WebApplicationContext webApplicationContext;

    private MockMvc mockMvc;

    @Before
    public void setUp() throws Exception {
        mockMvc = webAppContextSetup(webApplicationContext).build();
    }
    ....
}


暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM