1 回答
TA贡献1744条经验 获得超4个赞
您需要将 TestService 放在 TestApiController 的构造函数中,以便在测试中创建对象时可以注入它。
public class TestApiController {
private TestFeedService testService; // This is an interface
@Autowired
public TestApiController(TestFeedService testService ) {
this.testService = testService;
}
@RequestMapping(path = "/api/process-message", method = RequestMethod.POST)
public ResponseEntity<?> processMessage(@RequestBody TestForm2 testForm) {
DataBO dataBO = convertBO(testForm);
testService.sendMessage(dataBO, false); // here I am getting testService = null and causing exception
return ResponseEntity.ok().build();
} // Some more code
所以你的测试是这样的:
public class testApiControllerTest {
private MockMvc mockMvc;
private TesApiController testApiController;
private TestFeedService testService;
@Before
public void setup() {
this.testService = mock(TestFeedService.class);
}
@Test
public void testProcessMessage() {
this.testApiController = new TestApiController(this.testService);
// More code
}}
希望它有帮助
添加回答
举报