[英]How to change a field in controller for test?
我有下一個控制器:
@EnableWebMvc
@RequestMapping("experiences")
@RestController("experience_controller")
public class ExperienceController {
@Autowired
private ExperienceManager mExperienceManager;
protected boolean mIsTest = false; //I need to replace by 'true'
@PostMapping(value = "new")
public ResponseEntity<ExperienceModel> add(
@RequestBody NewExperienceModel newExperience
) {
if (!mIsTest) {
ExperienceUtils.validate(newExperience);
}
Experience experience = newExperience.toExperience();
if (!mExperienceManager.add(experience)) {
throw new InternalServerException(ServerError.INTERNAL);
}
return new ResponseEntity<>(new ExperienceModel(experience),
HttpStatus.CREATED);
}
}
和我的應用程序測試類:
@TestPropertySource(properties = { "com.contedevel.virto.experience.controllers.ExperienceController.mIsTest=true" })
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ExperienceControllerTest {
@Autowired
private MockMvc mMockMvc;
private ObjectMapper mMapper;
private NewExperienceModel mModel;
private String mExperienceId;
@Before
public void setUp() {
mMapper = new ObjectMapper();
UUID userId = UUID.randomUUID();
UUID gameId = UUID.randomUUID();
UUID achievementId = UUID.randomUUID();
float value = 50f;
mModel = new NewExperienceModel(userId, gameId, achievementId, value);
}
@Test()
public void testOrder() throws Exception {
testPost();
}
private void testPost() throws Exception {
String json = mMapper.writeValueAsString(mModel);
final String url = "/experiences/new";
MvcResult result = mMockMvc.perform(post(url)
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.content(json))
.andDo(print())
.andExpect(status().isCreated())
.andReturn();
String response = result.getResponse()
.getContentAsString();
JSONObject obj = new JSONObject(response);
mExperienceId = obj.getString(ExperienceKeys.ID);
}
}
我需要在控制器中設置mIsTest = true
...當然,我知道此代碼是錯誤的,但是如何做到這一點呢? 還是我需要每次手動更改它?
使用@Value怎么樣?
public class ExperienceController {
...
@Value("${flag.test:false}")
protected boolean mIsTest;
...
}
和測試代碼
...
@TestPropertySource(properties = {"flag.test = true"})
public class ExperienceControllerTest {
...
}
mIsTest的默認值為false,您可以使用flag.test屬性(或其他屬性)更改mIsTest的值。 您可以使用屬性文件和活動配置文件更改其值。
如果您想獲得@Value的快速指南,請參考: http : //www.baeldung.com/spring-value-annotation
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.