In my project I am creating a rest endpoint which is responsible to consume grpc service response. Now I want to write testcase for the controller class but the Junit test cases returning me null null values.
MyController.java
@RestController
@RequestMapping("/v1")
public class MyController {
@Autowired
private MyConsumerService consumer;
public MyController(MyConsumerService consumer) {
this.consumer=consumer;
}
@GetMapping("/data")
public ResponseEntity<Records> getData(@RequestParam("data") String data) {
Records records = consumer.getGrpcResponse(data);
return new ResponseEntity<>(Records, HttpStatus.OK);
}
}
MyConsumerServiceImpl.java:
public class MyConsumerServiceImpl implements MyConsumerService {
@GrpcClient("user-grpc-service")
private userGrpc.userBlockingStub stub;
@Override
public Records getGrpcResponse(data) {
Records records = new Records();
UserRequest request = UserRequest.newBuilder()
.setUserName(data)
.build();
APIResponse response = stub.userRequest(request);
records.setUserName(response.getUserName());
return records;
}
}
MyControllerTest.java:
@ExtendWith(MockitoExtension.class)
public class MyControllerTest {
private MyConsumerService mockerService;
private MyController controller;
@BeforeEach
void setup(){
mockerService = mock(MyConsumerService.class);
controller = new MyController(mockerService);
}
@Test
public void shouldGet(){
final var data="Hello";
when(mockerService.getGrpcResponse(data)).thenReturn(new Records());
final var responseEntity=controller.getData(data);
assertEquals(responseEntity.getBody(),new Records());
}
}
responseEntity.getBody()
is returning null
.
Normal flow is working fine but with Junit when I am mocking the client service call, it is returning null
.
I am confused why always it is returning null
. Any idea where I am getting wrong.
you have not added when then statement for service.getData(), and below stubbing have not been called any where
when(mockerService.getGrpcResponse(data)).thenReturn(new Records());
use when then to mock service.getData() like this,
when(mockerService.getData(data)).thenReturn(new Records());
annotate this 'MyControllerTest' class with @WebMvcTest(MyController.class) and the rerun it will work, otherwise its not able to mock actual controller class.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.