mock when为restemplate返回null

mm5n2pyu  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(674)

我尝试测试一个简单的post-rest调用,但是有一个nullpointerexception。
我的控制器:

@RestController
@RequestMapping("/v1/mail")
@Slf4j
public class EmailForwardController {

    @Autowired
    EmailForwardConfig emailConfig;

    @Autowired
    RestTemplate restTemplate;

    @PostMapping("/forward")
    public ResponseEntity<String> setupEmailForward(@RequestParam String fromEmail, @RequestParam String toEmail, @RequestParam String referenceId) {
        log.info("Email Forward: from=" + fromEmail + " to=" + toEmail + " reference=" + referenceId);
        String uri = emailConfig.getUrl() + "forward";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("from", fromEmail);
        jsonObject.put("to", toEmail);
        jsonObject.put("clientId", referenceId);
        HttpEntity<String> httpEntity = new HttpEntity<>(jsonObject.toJSONString());
        ResponseEntity<String> response = restTemplate.postForEntity(uri, httpEntity, String.class);
        System.out.println(response); // -> this is null at UNIT Test
        if (response.getBody() == null) {
            log.error("No response for call!");
            return new ResponseEntity<>("Problem!", HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return new ResponseEntity<>(response.getBody(), response.getStatusCode());

    }

}

我的单元测试:

@RunWith(MockitoJUnitRunner.class)
@SpringBootTest(classes = EmailForward.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class ServiceTest {

    @InjectMocks
    EmailForwardController emailForwardController;

    @Mock
    RestTemplate restTemplate;

    @Mock
    EmailForwardConfig emailConfig;

    @Before
    public void setup() {

    }

    @Test
    public void test_forward_ok() {
        assertNotNull(restTemplate);
        assertNotNull(emailForwardController);
//        System.out.println(Mockito.verify(restTemplate).postForEntity(any(), any(), any()));
        Mockito.when(restTemplate.postForEntity(any(), any(), any())).thenReturn(new ResponseEntity<>("done", HttpStatus.OK));
        ResponseEntity<String> responseEntity = emailForwardController.setupEmailForward("test", "test", "test");
        assertNotNull(responseEntity);
        assertNotNull(responseEntity.getStatusCode());
        assertNotNull(responseEntity.getBody());
        assertEquals(responseEntity.getBody(), "Done");
        assertEquals(responseEntity.getStatusCode(), HttpStatus.OK);
    }

}

由于以下错误,此测试失败:nullpointerexception,响应responseentity对象正好为null。
验证输出显示:

Wanted but not invoked:
restTemplate.postForEntity(
    <any>,
    <any>,
    <any>
);
-> at xx.xxx.ms.oauth2.ServiceTest.test_forward_ok(ServiceTest.java:42)
Actually, there were zero interactions with this mock.

你知道为什么回答是空的吗?我为测试使用了正确的注解,因此应该注入mock。也许我错过了一些重要的东西,因为如果我把 @Mock EmailForwardConfig emailConfig; 此对象在restcontroller中为空。我觉得我忘了什么,但我想不出来。

juzqafwq

juzqafwq1#

您对restemplate.postforentity的嘲弄是不正确的。
将你的嘲笑改为:

Mockito.when(restTemplate.postForEntity(any(), any(), any())).thenReturn(new ResponseEntity<>("done", HttpStatus.OK));

收件人:

Mockito.when(restTemplate.postForEntity(anyString(),any(),
                any(Class.class))).thenReturn(new ResponseEntity<>("done", HttpStatus.OK));

我试过了:

@ExtendWith(MockitoExtension.class)
public class TestcontrollerTest {

    @InjectMocks
    Testcontroller emailForwardController;
    @Mock
    RestTemplate restTemplate;

    @Before
    public void setup() {

    }

    @Test
    public void test_forward_ok() {
        assertNotNull(restTemplate);
        assertNotNull(emailForwardController);
//        System.out.println(Mockito.verify(restTemplate).postForEntity(any(), any(), any()));
        Mockito.when(restTemplate.postForEntity(anyString(),any(),
                any(Class.class))).thenReturn(new ResponseEntity<>("done", HttpStatus.OK));
        ResponseEntity<String> responseEntity = emailForwardController.setupEmailForward("test", "test", "test");
        assertNotNull(responseEntity);
        assertNotNull(responseEntity.getStatusCode());
        assertNotNull(responseEntity.getBody());
        assertEquals(responseEntity.getBody(), "done");
        assertEquals(responseEntity.getStatusCode(), HttpStatus.OK);
    }
}
yeotifhr

yeotifhr2#

我发现问题似乎是变量的顺序不同,需要检查文件。
@mock应该在@injectmock之前

@Mock
    RestTemplate restTemplate;

    @InjectMocks
    Testcontroller emailForwardController;

相关问题