gpt4 book ai didi

java - 如何在 JUnit 测试中初始化对象?

转载 作者:行者123 更新时间:2023-12-01 19:36:57 26 4
gpt4 key购买 nike

我正在尝试进行 JUnit 测试来测试 Controller 。

我的 Controller 包括:

    @Autowired
private OrderManager orderManager;

@RequestMapping(value = "/getOrderList", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> getOrderTables(OrderSearchDto orderSearchDto) {
...
orderHdrTables = orderManager.findAllOrders(orderSearchDto);
...
}

我的测试是:

@RunWith(MockitoJUnitRunner.class)
public class FilterActivityTest {

@InjectMocks
private OrderHdrController orderHdrController;

private MockMvc mockMvc;

@Before
public void setup() {
this.mockMvc = MockMvcBuilders.standaloneSetup(orderHdrController).build();
}

@Test
public void testActivityFilter() throws Exception {

OrderSearchDto orderSearchDto = new OrderSearchDto();
OrderSearchPanelDto orderSearchPanelDto = new OrderSearchPanelDto();
List <String> activityTypes = Arrays.asList("DELIVERY","START_UPLOAD");
orderSearchPanelDto.setActivityTypes(activityTypes);
orderSearchDto.setOrderSearchPanelDto(orderSearchPanelDto);

mockMvc.perform(MockMvcRequestBuilders.post("/orders/getOrderList")
.content(asJsonString(orderSearchDto))
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)).andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.data.data[0].tripNo", is("SG1606LLR08469")))
.andExpect(jsonPath("$.data.data[1].tripNo", is("SG1606LLR08470")));;
}

private static String asJsonString(final Object obj) {
try {
final ObjectMapper mapper = new ObjectMapper();
final String jsonContent = mapper.writeValueAsString(obj);
return jsonContent;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}

但是在测试调试期间,我在 Controller 中发现 orderManager 为 null。我可以做什么来初始化它?

最佳答案

我对你的测试做了一些修改。请尝试这个。

import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {
FilterActivityTest.Config.class,
OrderHdrController.class,
})
public class FilterActivityTest {

@Configuration
static class Config {
@Bean
OrderManager orderManager() {
return mock(OrderManager.class);
}
}

@Autowired
private OrderHdrController orderHdrController;

@Before
public void setup() {
this.mockMvc = MockMvcBuilders.standaloneSetup(orderHdrController).build();
//remember to mock orderManager.findAllOrders here
}


}

关于java - 如何在 JUnit 测试中初始化对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59205548/

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