gpt4 book ai didi

java - 如何更改 Controller 中的字段以进行测试?

转载 作者:行者123 更新时间:2023-12-02 11:41:36 25 4
gpt4 key购买 nike

我有下一个 Controller :

@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);
}
}

我需要在我的 Controller 中设置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 的值。您可以使用属性文件和 Activity 配置文件更改其值。

如果您想快速了解@Value,请参阅此处:http://www.baeldung.com/spring-value-annotation

关于java - 如何更改 Controller 中的字段以进行测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48510868/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com