当我使用我的测试类中运行以下代码时:
Mockito.when(accountHelper.convertAccountToJson(account)).thenReturn(jsonObject);
它返回jsonObject。但是,在我的AccountController中,以下代码返回null:
JSONObject accountJson = accountHelper.convertAccountToJson(account);
有人可以解释为什么模拟回应没有被反映出来吗?提前致谢。
这是我的代码: 识别TestClass
@RunWith(MockitoJUnitRunner.class)
public class AccountControllerTest {
@InjectMocks private AccountController accountController;
@Mock private AccountHelper accountHelper;
MockMvc mockMvc;
@Before
public void setup() throws Exception {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(accountController).build();
}
@Test
public void createAccountEmptyMessage() throws Exception{
String jsonString = "{}";
String expectedReturnBody = "{\"name\":"test"}";
Account account = new Account(test);
JSONObject jsonObject = new JSONObject("{\"name\":"test"}");
Mockito.when(accountHelper.convertAccountToJson(account)).thenReturn(jsonObject);
mockMvc.perform(post("/createAccount").contentType(MediaType.APPLICATION_JSON).characterEncoding("UTF-8")
.accept(MediaType.APPLICATION_JSON).content(jsonString))
.andExpect(content().string(expectedReturnBody));
}
}
助手类
@Component
public class AccountHelper {
public JSONObject convertAccountToJson(Account account) {
String jsonString;
JSONObject json;
Gson gson = new Gson();
try{
jsonString = gson.toJson(account);
json = new JSONObject(jsonString);
logger.info(jsonString);
} catch (Exception e) {
return null;
}
return json;
}
控制器
@RestController
public class AccountController {
@Autowired private AccountService accountService;
@Autowired private AccountHelper accountHelper;
@RequestMapping(method = RequestMethod.POST, value = "/createAccount")
public ResponseEntity<Object> createAccount(@RequestBody(required= false) Account account) {
try {
JSONObject accountJson = accountHelper.convertAccountToJson(account); //Return null
//Create Account
return new ResponseEntity(accountJson.toString(), HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}