我有這個測驗:
@ExtendWith(SpringExtension.class)
@WebMvcTest(AuthController.class)
@TestPropertySource("classpath:application.properties")
class AuthControllerTest {
@Autowired
private MockMvc mvc;
@Autowired
AuthTokenFilter authTokenFilter;
@MockBean
AuthEntryPointJwt authEntryPointJwt;
@MockBean
JwtUtils jwtUtils;
@Autowired
private ObjectMapper objectMapper;
@MockBean
UserDetailsServiceImpl userDetailsServiceImpl;
@MockBean
AuthenticationManager authenticationManager;
@MockBean
Authentication authentication;
@MockBean
SecurityContext securityContext;
@Test
void test1withEnabledTrue() {
}
@Test
void test2WithEnabledTrue() {
}
@Test
void cannotRegisterUserWhenRegistrationsAreDisabled() throws Exception {
var userToSave = validUserEntity("username", "password");
var savedUser = validUserEntity("username", "a1.b2.c3");
when(userDetailsServiceImpl.post(userToSave)).thenReturn(savedUser);
mvc.perform(post("/api/v1/auth/register/").contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsBytes(userToSave))).andExpect(status().isCreated())
.andExpect(jsonPath("$.status", is("registrations are disabled")));
}
private static UsersEntity validUserEntity(String username, String password) {
return UsersEntity.builder().username(username).password(password).build();
}
}
這是控制器(被測類)中的相關部分:
@Value("${app.enableRegistration}")
private Boolean enableRegistration;
private Boolean getEnableRegistration() {
return this.enableRegistration;
}
@PostMapping("/register")
@ResponseStatus(HttpStatus.CREATED)
public Map<String, String> post(@RequestBody UsersDTO usersDTO) {
Map<String, String> map = new LinkedHashMap<>();
if (getEnableRegistration()) {
[...]
map.put("status", "ok - new user created");
return map;
}
map.put("status", "registrations are disabled");
return map;
}
我有這個application.properties,src/test/resources我需要覆寫它,僅用于我的單個測驗名為cannotRegisterUserWhenRegistrationsAreDisabled
app.enableRegistration=true
可能我可以使用另一個檔案“application.properties”和另一個類測驗,但我正在尋找更智能的解決方案。
uj5u.com熱心網友回復:
您可以簡單地配置 inlineproperties的@TestPropertySource優先級高于從locations/加載的屬性value:
@WebMvcTest(AuthController.class)
@TestPropertySource(locations = "classpath:application.properties" ,properties="app.enableRegistration=true" )
class AuthControllerTest {
}
中指定的所有行內屬性properties將覆寫在application.properties
uj5u.com熱心網友回復:
我認為您正在尋找的是注釋,這是 Stackoverflow here@TestProperty上問題的答案。但是,這僅適用于班級級別,而不僅僅適用于一項測驗。
您可能需要創建一個新的測驗類并將測驗添加到值需要的位置false。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/429139.html
