Postman GET request is giving 404 not found in postman for my endpoint http://localhost:8080/employee/all - get

Can anyone help me in what wrong I am doing in my spring application? I am getting 404 not found for http://localhost:8080/employee/all endpoint.
Postman error -
{
"timestamp": "2023-02-03T10:33:58.409+00:00",
"status": 404,
"error": "Not Found",
"path": "/employee/all"
}
Project Structure
This is the controller class -
package website.sample.employee.management.system;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import website.sample.employee.management.system.model.Employee;
import website.sample.employee.management.system.service.EmployeeService;
#RestController
#RequestMapping("/employee")
public class EmployeeResource {
private final EmployeeService employeeService;
public EmployeeResource(EmployeeService employeeService) {
this.employeeService = employeeService;
}
#GetMapping("/all")
public ResponseEntity<List<Employee>> getAllEmployees() {
List<Employee> employees = employeeService.findAllEmployees();
return new ResponseEntity<>(employees, HttpStatus.OK);
}
#GetMapping("/find/{id}")
public ResponseEntity<Employee> getEmployeeById(#PathVariable("id") Long id) {
Employee employee = employeeService.findEmployeeById(id);
return new ResponseEntity<>(employee, HttpStatus.OK);
}
#PostMapping("/add")
public ResponseEntity<Employee> addEmployee(#RequestBody Employee employee) {
Employee newEmployee = employeeService.addEmployee(employee);
return new ResponseEntity<>(newEmployee, HttpStatus.CREATED);
}
#PutMapping("/update")
public ResponseEntity<Employee> updateEmployee(#RequestBody Employee employee) {
Employee updateEmployee = employeeService.updateEmployee(employee);
return new ResponseEntity<>(updateEmployee, HttpStatus.OK);
}
#DeleteMapping("/delete/{id}")
public ResponseEntity<?> deleteEmployee(#PathVariable("id") Long id) {
employeeService.deleteEmployee(id);
return new ResponseEntity<>(HttpStatus.OK);
}
}
EmployeeRepo class -
package website.sample.employee.management.system.repo;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import website.sample.employee.management.system.model.Employee;
public interface EmployeeRepo extends JpaRepository<Employee, Long> {
void deleteEmployeeById(Long id);
Optional<Employee> findEmployeeById(Long id);
}
EmployeeService class -
package website.sample.employee.management.system.service;
import java.util.List;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import website.sample.employee.management.system.exception.UserNotFoundException;
import website.sample.employee.management.system.model.Employee;
import website.sample.employee.management.system.repo.EmployeeRepo;
#Service
public class EmployeeService {
private final EmployeeRepo employeeRepo;
#Autowired
public EmployeeService(EmployeeRepo employeeRepo) {
this.employeeRepo = employeeRepo;
}
public Employee addEmployee(Employee employee) {
employee.setEmployeeCode(UUID.randomUUID().toString());
return employeeRepo.save(employee);
}
public List<Employee> findAllEmployees() {
return employeeRepo.findAll();
}
public Employee updateEmployee(Employee employee) {
return employeeRepo.save(employee);
}
public Employee findEmployeeById(Long id) {
return employeeRepo.findEmployeeById(id)
.orElseThrow(() -> new UserNotFoundException("User by id " + id + " was not found"));
}
public void deleteEmployee(Long id) {
employeeRepo.deleteEmployeeById(id);
}
}
This is the error I get in postman -
{
"timestamp": "2023-02-03T10:33:58.409+00:00",
"status": 404,
"error": "Not Found",
"path": "/employee/all"
}
I am trying to use the endpoint http://localhost:8080/employee/all
Please let me know if you know why postman is not able to find this end point.
I have tried some ways for this issue on the internet but cannot debug it.

Related

Quarkus Panache Mockito fails

I struggle with mocking a Panache repository.
Here is the Entity:
import javax.persistence.*;
#Entity
public class Thing {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false)
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
Simple repository:
import io.quarkus.hibernate.orm.panache.PanacheRepository;
import javax.enterprise.context.ApplicationScoped;
#ApplicationScoped
public class ThingRepository implements PanacheRepository<Thing> {
}
This is the resource:
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.List;
#Path("/things")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public class ThingResource {
#Inject
ThingRepository thingRepository;
#GET
public List<Thing> list() {
return thingRepository.listAll();
}
}
and a simple test where I try to mock the repository:
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.mockito.InjectMock;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertNotNull;
#QuarkusTest
class ThingResourceTest {
private Thing thing;
#Inject ThingResource thingResource;
#InjectMock ThingRepository thingRepository;
#BeforeEach
void setUp() {
Thing thing = new Thing();
thing.setId(1L);
}
#Test
void getAll() {
List<Thing> things = new ArrayList<Thing>();
things.add(thing);
Mockito.when(thingRepository.listAll()).thenReturn(things);
List<Thing> response = thingResource.list();
assertNotNull(response);
assertNotNull(response.get(0));
}
}
The test fails because the response list is <null>.
The debugger tells me the thingRepository is actually mocked. But for some reason Mockito.when().thenReturns() does not return the list I set up.
What am I missing?
Thank you for any help.
I had the thing double declared. One time as class variable, and again in setUp(). Bummer. I apologize for the noise.

My controller code is not reachable from the MockMvc get request and i am always getting 404

I am trying to mock my controller and write testcases for it. But when I tried to debug the Test class the control is not getting into my Controller class. I am not sure what I am doing wrong here.
Please help me to resolve this as I am stuck on this for almost more that 3 hours.
My Service class
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bnpp.leavemanagement.dao.DepartmentRepository;
import com.bnpp.leavemanagement.model.DepartmentModel;
#Service
public class DepartmentService
{
#Autowired
DepartmentRepository depRepo;
public List<DepartmentModel> listDepartment = new ArrayList<>();
public List<DepartmentModel> getAllDepartments()
{
List<DepartmentModel> allDepartment = depRepo.findAll();
return allDepartment;
}
public DepartmentModel fetchDepartmentById( int id)
{
DepartmentModel depDetail = null;
try
{
depDetail = depRepo.findById(Long.valueOf(id)).get();
}
catch(Exception ex)
{
depDetail = null;
}
return depDetail;
}
public DepartmentModel addDepartment(DepartmentModel depDetail)
{
DepartmentModel depExists = null;
if (listDepartment.size() > 0)
{
depExists = listDepartment.stream()
.filter(d -> d.getName().equalsIgnoreCase(depDetail.getName()))
.findFirst()
.orElse(null);
}
//Below condition is to restrict duplicate department creation
if(depExists == null)
{
depRepo.save(depDetail);
listDepartment.add(depDetail);
}
else
{
return null;
}
return depDetail;
}
public DepartmentModel updateDepartment(DepartmentModel depDetail)
{
DepartmentModel depUpdate = null;
try
{
depUpdate = depRepo.findById(depDetail.getId()).get();
depUpdate.setName(depDetail.getName());
depRepo.save(depUpdate);
}
catch(Exception ex)
{
depUpdate = null;
}
return depUpdate;
}
public DepartmentModel deleteDepartment(DepartmentModel depDetail)
{
try
{
depRepo.deleteById(depDetail.getId());
}
catch(Exception ex)
{
return null;
}
return depDetail;
}
}
My Test Class
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.ArrayList;
import java.util.List;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Description;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.web.context.WebApplicationContext;
import com.bnpp.leavemanagement.controller.DepartmentController;
import com.bnpp.leavemanagement.model.DepartmentModel;
import com.bnpp.leavemanagement.service.DepartmentService;
#ExtendWith(MockitoExtension.class)
#WebMvcTest(DepartmentController.class)
#ContextConfiguration(classes = com.bnpp.leavemanagementsystem.LeaveManagementSystemApplicationTests.class)
public class DepartmentControllerTest {
#MockBean
DepartmentService depService;
#Autowired
private MockMvc mockMvc;
#InjectMocks
DepartmentController departmentController;
#Autowired
private WebApplicationContext webApplicationContext;
#Test
#Description("Should return a list of DepartmentModel objects when called")
void shouldReturnListOfDepartmentModel() throws Exception
{
DepartmentModel depModel = new DepartmentModel();
depModel.setId(1L);
depModel.setName("Mock");
List<DepartmentModel> listDepmodel = new ArrayList<>();
listDepmodel.add(depModel);
Mockito.when(depService.getAllDepartments()).thenReturn(listDepmodel);
mockMvc.perform(MockMvcRequestBuilders.get("/department"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.size()", Matchers.is(1)))
.andExpect(MockMvcResultMatchers.jsonPath("$[0].id").value(1))
.andExpect(MockMvcResultMatchers.jsonPath("$[0].name").value("Mock"));
}
}
My Controller class
package com.bnpp.leavemanagement.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.bnpp.leavemanagement.dao.DepartmentRepository;
import com.bnpp.leavemanagement.model.DepartmentModel;
import com.bnpp.leavemanagement.service.DepartmentService;
#RestController
public class DepartmentController
{
#Autowired
DepartmentService depService;
#GetMapping("/department")
public ResponseEntity<List<DepartmentModel>> getDepartments()
{
List<DepartmentModel> allDepartment = depService.getAllDepartments();
if(allDepartment.size() == 0)
{
return new ResponseEntity( HttpStatus.NOT_FOUND);
}
return new ResponseEntity( allDepartment, HttpStatus.OK);
}
#GetMapping("/department/{id}")
public ResponseEntity<DepartmentModel> fetchDepartmentById(#PathVariable("id") int id)
{
DepartmentModel resDep = depService.fetchDepartmentById(id);
if(resDep == null)
{
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
else
{
return new ResponseEntity( resDep, HttpStatus.OK);
}
}
#PostMapping("/department/create")
public ResponseEntity<DepartmentModel> createDepartment(#RequestBody DepartmentModel depNew)
{
DepartmentModel resDep = depService.addDepartment(depNew);
if(resDep == null)
{
return new ResponseEntity(HttpStatus.EXPECTATION_FAILED);
}
else
{
return new ResponseEntity( resDep, HttpStatus.CREATED);
}
}
#PutMapping("/department/update")
public ResponseEntity<DepartmentModel> updateDepartment(#RequestBody DepartmentModel depNew)
{
DepartmentModel resDep = depService.updateDepartment(depNew);
if(resDep == null)
{
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
else
{
return new ResponseEntity( resDep, HttpStatus.OK);
}
}
#DeleteMapping("/department/delete")
public ResponseEntity<DepartmentModel> deleteDepartment(#RequestBody DepartmentModel depDel)
{
DepartmentModel resDep = depService.deleteDepartment(depDel);
if(resDep == null)
{
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
else
{
return new ResponseEntity(HttpStatus.OK);
}
}
}
The minimal viable test setup to use MockMvc with #WebMvcTest is the following:
#WebMvcTest(DepartmentController.class)
class DepartmentControllerTest {
#MockBean
DepartmentService depService;
#Autowired
private MockMvc mockMvc;
#Test
#Description("Should return a list of DepartmentModel objects when called")
void shouldReturnListOfDepartmentModel() throws Exception {
DepartmentModel depModel = new DepartmentModel();
depModel.setId(1L);
depModel.setName("Mock");
List<DepartmentModel> listDepmodel = new ArrayList<>();
listDepmodel.add(depModel);
Mockito.when(depService.getAllDepartments()).thenReturn(listDepmodel);
mockMvc.perform(MockMvcRequestBuilders.get("/department"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.size()", Matchers.is(1)))
.andExpect(MockMvcResultMatchers.jsonPath("$[0].id").value(1))
.andExpect(MockMvcResultMatchers.jsonPath("$[0].name").value("Mock"));
}
}
Explanation:
#InjectMocks is not necessary as with #MockBean you're adding a mocked version of DepartmentService to your Spring TestContext and Spring DI's mechanism will inject it to your DepartmentController
#ExtendWith(SpringExtension.class) is also redundant, as the meta annotation #WebMvcTest already activates the SpringExtension.class
You don't need #ContextConfiguration here as #WebMvcTest takes care to detect your Spring Boot entrypoint class and start a sliced context
If the test still doesn't work, please add all your dependencies, the way you structure your code, and your main Spring Boot class (annotated with #SpringBootApplication).
Further reads that might shed some light on this:
Difference Between #Mock and #MockBean
Guide to Testing Spring Boot Applications With MockMvc

What is the argument matcher for a Mono type parameter?

Class under test:
import java.time.Duration;
import java.time.Instant;
import java.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
public class ServiceProcessorImpl implements ServiceProcessor {
#Autowired
private WebClient webClient;
#Override
public Mono<ServiceResponse> fetchOffersByItemIdAndStoreId(Mono<List<PriceAndOfferRequest>> list) {
String url = "<some url>";
Mono<ServiceResponse> response = webClient
.post()
.uri(url)
.headers(httpHeaders -> getHeaders(httpHeaders))
.body(list,List.class)
.retrieve()
.onStatus(HttpStatus::isError, clientResponse -> {
log.error("Error on API Calling : {}", clientResponse.statusCode());
return Mono.empty();
})
.bodyToMono(PnOServiceResponse.class);
return response;
}
}
Test Case:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
#RunWith(SpringRunner.class)
public class ServiceProcessorImplTest {
#Mock
private static WebClient webClientMock;
#Mock
private WebClient.RequestHeadersSpec requestHeadersSpecMock;
#Mock
private WebClient.RequestHeadersUriSpec requestHeadersUriSpecMock;
#Mock
private WebClient.RequestBodySpec requestBodySpecMock;
#Mock
private WebClient.RequestBodyUriSpec requestBodyUriSpecMock;
#Mock
private WebClient.ResponseSpec responseSpecMock;
#InjectMocks
static ServiceProcessorImpl pnOServiceProcessor;
#Test
public void test_whenErrorFromService_thenMonoEmpty() {
Mockito.when(webClientMock.post()).thenReturn(requestBodyUriSpecMock);
Mockito.when(requestBodyUriSpecMock.uri(Mockito.anyString())).thenReturn(requestBodySpecMock);
Mockito.when(requestBodySpecMock.headers(Mockito.any())).thenReturn(requestBodySpecMock);
Mockito.when(requestBodySpecMock.body(Mockito.any(Mono.class), Mockito.any(Class.class))).thenReturn(requestHeadersSpecMock);
Mockito.when(requestHeadersSpecMock.retrieve()).thenReturn(responseSpecMock);
Mockito.when(responseSpecMock.onStatus(Mockito.any(), Mockito.any())).thenReturn(responseSpecMock);
Mockito.when(responseSpecMock.bodyToMono(Mockito.eq(PnOServiceResponse.class))).thenReturn(Mono.empty());
Mono<List<PriceAndOfferRequest>> reqList = createPriceAndOfferRequestList();
Mono<PnOServiceResponse> pnOServiceResponseMono = pnOServiceProcessor.fetchOffersByItemIdAndStoreId(reqList);
StepVerifier.create(pnOServiceResponseMono)
.expectNextCount(0)
.verifyComplete();
}
private Mono<List<PriceAndOfferRequest>> createPriceAndOfferRequestList() {
PriceAndOfferRequest pnoRequest = new PriceAndOfferRequest();
pnoRequest.setItemId("12345");
pnoRequest.setStoreNumber("store12345");
List<PriceAndOfferRequest> list = Arrays.asList(pnoRequest);
return Mono.just(list);
}
private Mono<PnOServiceResponse> createMockPnOResponse() {
PnOServiceResponse pnOServiceResponse = new PnOServiceResponse();
OfferPriceDTO offerPriceDTO = new OfferPriceDTO();
PnOItem item = new PnOItem();
item.setItemId("12345");
offerPriceDTO.setItems(Arrays.asList(item));
pnOServiceResponse.setOfferPriceDTO(offerPriceDTO);
return Mono.just(pnOServiceResponse);
}
}
The code gives NullPointerException while calling .body() on the webClient in fetchOffersByItemIdAndStoreId method. Looks like there is some issue with the ArgumentMatcher in the test case when mocking the call to body() in Mockito.when(requestBodySpecMock.body(Mockito.any(Mono.class), Mockito.any(Class.class))).thenReturn(requestHeadersSpecMock);
Resolved.
Mockito.any(Object.class) worked me.
Mockito.when(requestBodySpecMock.body(Mockito.any(Object.class), Mockito.any(Class.class))).thenReturn(requestHeadersSpecMock);
You can use the generic matcher ArgumentMatchers.any()

Cucumber testng with PowerMockTestCase to mock static classes

I am using cucumber BDD, testng, java to write some BDD test. I would like to mock static classes in order to write my test. However when I write this testrunner, it fails to initialize the BDD scenarios.
Complete Example(note the commented line PrepareForTest) :
import gherkin.events.PickleEvent;
import io.cucumber.testng.CucumberOptions;
import io.cucumber.testng.PickleEventWrapper;
import io.cucumber.testng.TestNGCucumberRunner;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.testng.PowerMockTestCase;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.util.concurrent.TimeUnit;
import static org.mockito.Matchers.any;
#CucumberOptions(
features = {
"src/test/resources/features/sample"
},
glue = {
"com.demo.stepdefinitions.sample"
},
plugin = {
"pretty",
"html:target/cucumber-reports/cucumber-pretty",
"json:target/cucumber-reports/sampple-report.json",
"rerun:target/cucumber-reports/sample-rerun.txt"
}
)
//#PrepareForTest({Util.class})
public class TestngWithDataproviderTest extends PowerMockTestCase {
private TestNGCucumberRunner testNGCucumberRunner;
private void mockActiveBucket() {
PowerMockito.mockStatic(Util.class);
PowerMockito.when(Util.getBucketId(any(Long.class))).thenReturn(3);
}
#BeforeClass(alwaysRun = true)
public void setUpClass() throws Exception {
testNGCucumberRunner = new TestNGCucumberRunner(this.getClass());
}
#Test(dataProvider = "users")
public void testMockStatic(String username){
System.out.println("username: " + username);
System.out.println("static test passed");
mockActiveBucket();
Assert.assertTrue(true);
}
#Test(groups = "cucumber scenarios", description = "Runs Cucumber Scenarios", dataProvider = "scenarios")
public void testCucumberCcenario(PickleEventWrapper pickleEvent) throws Throwable {
PickleEvent event = pickleEvent.getPickleEvent();
mockActiveBucket();
testNGCucumberRunner.runScenario(pickleEvent.getPickleEvent());
Assert.assertTrue(true);
}
#DataProvider(name = "scenarios")
public Object[][] scenarios() {
Object[][] scenarios = testNGCucumberRunner.provideScenarios();
return new Object[][]{{scenarios[0][0]}};
}
#DataProvider(name = "users")
public Object[][] users() {
return new Object[][]{{"user1"}, {"user2"}};
}
}
class Util {
public static int getBucketId(long eventTimestamp){
Long minsPast5MinBoundary = (eventTimestamp % TimeUnit.MINUTES.toMillis(5))/TimeUnit.MINUTES.toMillis(1);
return minsPast5MinBoundary.intValue();
}
}
The above test fails to load BDD scenarios dataProvider if I enable PrepareForTest annotation on the test. However, the other test which uses dataProvider works fine in both cases(enable or disable PrepareForTest)
ERROR:
Data provider mismatch
Method: testCucumberCcenario([Parameter{index=0, type=io.cucumber.testng.PickleEventWrapper, declaredAnnotations=[]}])
Arguments: [(io.cucumber.testng.PickleEventWrapperImpl) "Sunday isn't Friday"]
at org.testng.internal.reflect.DataProviderMethodMatcher.getConformingArguments(DataProviderMethodMatcher.java:45)
at org.testng.internal.Parameters.injectParameters(Parameters.java:796)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:983)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
at org.testng.TestRunner.privateRun(TestRunner.java:648)
at org.testng.TestRunner.run(TestRunner.java:505)
As a side effect of this, I am unable to mock static methods of util class while writing the BDD. I am new to cucumber BDD. Any help/pointers is appreciated.
After getting some help to root cause from #help-cucumber-jvm slack channel, I was able to root cause it to testng+powermock with dataproviders using custom classes.
For example this test fails
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.testng.PowerMockTestCase;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.ObjectFactory;
import org.testng.annotations.Test;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import static org.mockito.Matchers.any;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
#PrepareForTest(Util2.class)
public class TestngWithDataproviderTestngTest extends PowerMockTestCase {
#ObjectFactory
public org.testng.IObjectFactory getObjectFactory() {
return new org.powermock.modules.testng.PowerMockObjectFactory();
}
private void mockActiveBucket() {
PowerMockito.mockStatic(Util.class);
PowerMockito.when(Util.getBucketId(any(Long.class))).thenReturn(3);
}
#Test(dataProvider = "users")
public void testMockStatic(MyTestCaseImpl myTestCase) {
System.out.println("myTestCase: " + myTestCase);
System.out.println("static test passed");
mockActiveBucket();
Assert.assertTrue(true);
}
#DataProvider(name = "users")
public Object[][] users() {
return new Object[][]{{new MyTestCaseImpl(5)}};
}
}
//interface MyTestCase {
//}
class MyTestCaseImpl { //implements MyTestCase{
int i;
public MyTestCaseImpl() {
}
public MyTestCaseImpl(int i) {
this.i = i;
}
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
}
class Util2 {
public static int getBucketId(long eventTimestamp) {
Long minsPast5MinBoundary = (eventTimestamp % TimeUnit.MINUTES.toMillis(5)) / TimeUnit.MINUTES.toMillis(1);
return minsPast5MinBoundary.intValue();
}
}
Here as mentioned, seems to be a known issue with a workaround. Hope this helps.

Keep getting errors when running JUnit test on my http client

I am creating a client to send requests to an API, and I am trying to write a Junit test but i keep getting this error.
Here is my client code which sends a request:
import io.netty.handler.codec.http.HttpResponse;
import io.vertx.core.AsyncResult;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.ext.web.client.HttpRequest;
import io.vertx.ext.web.client.WebClient;
public class LoginCoreClient {
private WebClient webclient;
private String requestURL;
private static Logger logger = LoggerFactory.getLogger(LoginCoreClient.class);
public LoginCoreClient(WebClient webclient, String requestURL) {
this.webclient = webclient;
this.requestURL = requestURL;
}
public void invokeCore(JsonObject request, java.util.function.Consumer<JsonObject> func){
webclient.post(requestURL)
.putHeader("content-type", "application/json")
.sendJson(request, ar -> {
if (ar.succeeded()) {
logger.info("succeeded: " + ar.succeeded());
logger.info("statusCode: " + ar.result().statusCode());
logger.info("body: " + ar.result().body());
logger.info("headers: " + ar.result().headers());
JsonObject response = new JsonObject();
// populate it
func.accept(response);
} else {
logger.info("Executed: " + ar.cause());
}
});
}
}
Here is the test class that i am using to test that the correct response is being sent back:
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.*;
import java.awt.List;
import javax.xml.ws.Response;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import io.netty.util.concurrent.Future;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.client.HttpRequest;
import io.vertx.ext.web.client.WebClient;
import io.vertx.junit5.VertxExtension;
import io.vertx.junit5.VertxTestContext;
#ExtendWith(VertxExtension.class)
public class LoginCoreTestTest {
private LoginCoreTest client;
//set up WebClient
private WebClient createMockWebClient(JsonObject mockResponse) {
WebClient mockWebClient = mock(WebClient.class);
HttpRequest<Buffer> mockRequest = mock(HttpRequest.class);
when(mockWebClient.post(any())).thenReturn(mockRequest);
when(mockRequest.putHeader(any(), any())).thenReturn(mockRequest);
doAnswer(new Answer() {
#Override
public Object answer(InvocationOnMock invocation) throws Throwable {
// TODO Auto-generated method stub
java.util.function.Consumer func = invocation.getArgument(1);
func.accept(mockResponse);
return null;
}
}).when(mockRequest).sendJson(any(), any());
return mockWebClient;
}
#Test
#DisplayName("Test response from client")
public void test() {
//request being sent
JsonObject request = new JsonObject().put("SSN", "123456789").put("Address", "123 main st").put("zip", "08888").put("dob", "012387");
//expected response
JsonObject response = new JsonObject().put("clientToken", "11oije311").put("clientID", "123ID");
//test setup
LoginCoreTest coreClient = new LoginCoreTest(createMockWebClient(response), "http://localhost:8080/core");
//test steps
coreClient.invokeCore(request, resp -> {
assertEquals(resp.getString("clientToken"), response.getString("clientToken"));
//end.finished();
});
}
}
And this is the error that i keep getting when trying to run the test:
Any idea why these errors are popping up when i try to run the test?
In Object answer(InvocationOnMock invocation) instead of
java.util.function.Consumer func = invocation.getArgument(1);
you should use
Handler<AsyncResult<HttpResponse<T>>> func = invocation.getArgument(1);

Resources