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
}}
希望它有幫助
添加回答
舉報