When more than one tests added to rest controller test why am I getting WebApplicationContext is required? - rest

This is very funny. When I ran my controller test with more than one tests I am getting the following error when i run it with maven, but works fine in eclipse Junit.java.lang.IllegalArgumentException: WebApplicationContext is required
at org.springframework.util.Assert.notNull(Assert.java:112)
at org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder.<init>(DefaultMockMvcBuilder.java:43)
at org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup(MockMvcBuilders.java:46)
at com.akrilist.rest.web.akripost.controller.AbstractRestControllerTest.setup(AbstractRestControllerTest.java:32)
at com.akrilist.rest.web.akripost.controller.AutoPostControllerTest.setup(AutoPostControllerTest.java:36) Then I ran one test commenting the other alternately (commented testA then run testB, then commented testB then run testA) both are passing. I have no idea what is happening when I put both of then are active tests. if any of you have clue please let me know. I have put my classes here.
AbstractRestControllerTest
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = { TestRestServiceConfig.class, WebAppConfig.class })
#WebAppConfiguration
public abstract class AbstractRestControllerTest {
protected MockMvc mockMvc;
#Autowired
protected WebApplicationContext webApplicationContext;
/*#Inject
protected UserAccountService userAccountServiceMock;*/
#Before
public void setup() {
/* Mockito.reset(userAccountServiceMock);*/
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
}
AutoPostControllerTest
public class AutoPostControllerTest extends AbstractRestControllerTest {
#Autowired
private AutoPostService autoPostServiceMock;
#Autowired
private AutoPostConverter autoPostConverterMock;
#Before
public void setup() {
// Mockito.reset(autoPostServiceMock);
// Mockito.reset(commentPostRepositoryMock);
super.setup();
}
#Test
public void testValidationErrorForNullProfileId() throws Exception {
String description = TestUtil.createStringWithLength(501);
AutoPost autoPost = new TestAutoPostBuilder().description(description).buildModel();
mockMvc.perform(post("/auto/post").contentType(TestUtil.APPLICATION_JSON_UTF8).content(TestUtil.convertObjectToJsonBytes(autoPost))).andExpect(status().isBadRequest())
.andExpect(content().contentType(TestUtil.APPLICATION_JSON_UTF8))
// .andExpect(jsonPath("$[]", hasSize(1)))
.andExpect(jsonPath("$.type", is("validation failure")));
verifyZeroInteractions(autoPostServiceMock);
}
#Test
public void testGet_shouldReturnPost() throws Exception {
String description = TestUtil.createStringWithLength(501);
String postId = TestUtil.createStringWithLength(16);
Integer profileId = 123456;
TestAutoPostBuilder testAutoPostBuilder = new TestAutoPostBuilder();
AutoPost post = testAutoPostBuilder.postId(postId).description(description).profileId(profileId).buildModel();
when(autoPostServiceMock.get(postId)).thenReturn(post);
when(autoPostConverterMock.convertTo(post)).thenReturn(testAutoPostBuilder.buildDto());
mockMvc.perform(get("/auto/post/" + postId).contentType(TestUtil.APPLICATION_JSON_UTF8)).andExpect(status().isOk()).andExpect(content().contentType(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$.postId", is(postId))).andExpect(jsonPath("$.profileId", is(profileId))).andExpect(jsonPath("$.links", hasSize(1)));
verify(autoPostServiceMock, times(1)).get(anyString());
verifyNoMoreInteractions(autoPostServiceMock);
}
}

I fixed this issue. It was because of parallel configuration of maven-surefire-plugin. I changed its value to 'classes', so the issue is over. There are two ways we can fix this issue. One is
<parallel>classes</parallel>
<threadCount>10</threadCount>
other way annotating the test class with #net.jcip.annotations.NotThreadSafe that required sequential execution.

Related

Junit , Mockito Integration with Vertx

I am new vertx wanted to know which is the best junit framework and references that we should went through.
I tried using couple of things with mockito but services are not getting injected.
Please help in this.
UPDATE:
My TestClass looks something like this
public class GroupModeTest {
private static final Logger logger = LoggerFactory.getLogger(GroupMode.class);
public static GroupModeService service;
public static GroupModeDao dao;
private GroupMode groupMode;
private static GroupModeDao daoMock;
#BeforeAll
static void setup() {
logger.info("Starting Unit Tests for GroupMode");
daoMock = mock(GroupModeDao.class);
dao = new GroupModeDao();
service = new GroupModeService(daoMock);
}
#BeforeEach
void init() {
logger.info("Mocking new GroupMode Entity");
this.groupMode = new GroupMode();
}
#Test
public void testFakeWithMockito() throws IOException {
IGroupModeDao iGroupModeDao = mock(IGroupModeDao.class);
GroupMode groupMode = new GroupMode();
groupMode.setId(1L);
groupMode.setModeType("unique");
groupMode.setCreatedBy(1);
groupMode.setCreatedOn(LocalDateTime.now());
groupMode.setUpdatedBy(1);
groupMode.setUpdatedOn(LocalDateTime.now());
Single<Long> expected=Single.just(1L);
when(iGroupModeDao.create(groupMode)).thenReturn(expected);
GroupModeService groupModeService = new GroupModeService(iGroupModeDao);
Single<Long> actual= groupModeService.rxCreate("unique",1);
assertEquals(expected, actual);
}
}

Mockito fails for Spring data JPA Page interface

#SpringBootTest
public class TestClass {
#Mock
private Page<Customer> pagedResult;
#Mock
private Pageable paging = PageRequest.of(0, 1);
#Mock
private CustomerRepository cutomerRepository;
#InjectMocks
private CustomerServiceImpl service;
#Test
void testss() {
Set<Integer> set = new HashSet<>();
set.add(1);
Pageable paging1 = PageRequest.of(0, 1);
Page<Customer> pa = new PageImpl<>(Arrays.asList(customer));
when(cutomerRepository.findByIdIn(set, paging1)).thenReturn(pa);
when(service.test(set)).thenReturn(Arrays.asList(customer));
assertEquals(customer.getName(), service.test(set).get(0).getgetName());
}
}
Implementation class
public class CustomerServiceImpl {
private CustomerRepository customerRepository ;
public CustomerServiceImpl(CustomerRepository customerRepository ) {
super();
this.customerRepository = customerRepository ;
}
#Override
public List<Customer> test(Set<Integer> ids) {
Pageable paging = PageRequest.of(0, 1);
Page<Customer> pagedResult = customerRepository.findByIdIn(ids, paging);
return pagedResult.toList();
}
}
I am trying to write the Junit test case for my pagination code using mockito but it fails as it is expecting the return type for method as Page.but I am returning List of Customers.When I return Page from method it works fine but if I return List is fails with below mentioned error
I am getting below error
org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
ArrayList cannot be returned by findByIdIn()
findByIdIn() should return Page
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
This exception might occur in wrongly written multi-threaded tests.
Please refer to Mockito FAQ on limitations of concurrency testing.
A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies -
with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.
I think something is messed with your code.
In Your code you have doctorRepository.findByIdIn Method bt in your test class it is cutomerRepository.findByIdIn.
I have added the below code as a reference with respect to your CustomerServiceImpl.
You can try the same way to execute your test.
SpringBootTest
public class TestClass {
#Mock
private Pageable paging;
#Mock
private CustomerRepository cutomerRepository;
#Mock
private DoctorRepository doctorRepository;
#InjectMocks
private CustomerServiceImpl service;
#Test
void testss() {
Doctor doctor = new Doctor();
doctor.setName("test name");
Set<Integer> set = new HashSet<>();
set.add(1);
PageImpl<Doctor> page = new PageImpl<>(Arrays.asList(doctor));
when(doctorRepository.findByIdIn(Mockito.any(), Mockito.any())).thenReturn(page);
List<Doctor> doctors= service.test(set);
assertEquals(doctor.getName(), doctors.get(0).getgetName());
}
}

Integration Tests for RESTEasy Endpoint

I want to perform integration tests on my REST endpoint but am running into issues.
Below is my endpoint. NOTE: I cannot change this part of the code.
#Path("/people")
public class PersonResource {
private final PersonService personService;
#Inject
public PersonResource(final PersonService personService) {
this.personService = personService;
}
#GET
#Produces("application/json")
public List<Person> getPersonList() {
return personService.getPersonList();
}
}
From what I've been able to find online, I have the following basic structure for my test.
public class PersonResourceTest {
private Dispatcher dispatcher;
private POJOResourceFactory factory;
#Before
public void setup() {
dispatcher = MockDispatcherFactory.createDispatcher();
factory = new POJOResourceFactory(PersonResource.class);
dispatcher.getRegistry().addResourceFactory(factory);
}
#Test
public void testEndpoint() throws URISyntaxException {
MockHttpRequest request = MockHttpRequest.get("people");
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
System.out.print("\n\n\n\n\n" + response.getStatus() + "\n\n\n\n\n");
System.out.print("\n\n\n\n\n" + response.getContentAsString() + "\n\n\n\n\n");
}
}
However, this results in the following error on the last line of the setup method.
java.lang.RuntimeException: RESTEASY003190: Could not find constructor for class: my.path.PersonResource
I explored the Registry API and thought maybe I should have been using addSingletonResource instead, so I changed the last line of setup to dispatcher.getRegistry().addSingletonResource(personResource); and added the following.
#Inject
private PersonResource personResource;
But that results in a NullPointerException on the last line of setup.
The sparse documentation on the mocking isn't very helpful. Can anyone point out where I'm going wrong? Thanks.
You need to do two things
Add a no arguments constructor to your source class:
public PersonResource() {
this(null)
}
In the test class, initialize the PersonResource class with an instance of PersonService class:
dispatcher.getRegistry().addSingletonResource(new PersonResource(new PersonService()));
If needed, the PersonService class can be mocked:
private Dispatcher dispatcher;
#Mock
private PersonService service;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
dispatcher = MockDispatcherFactory.createDispatcher();
PersonResource resource= new PersonResource(service);
ispatcher.getRegistry().addSingletonResource(resource);
}
Hope it helps!

spring webclient unit test with mockito

I'm trying to write a test for my controller (which has an autowired field pageModelService)
here is my test class:
#RunWith(MockitoJUnitRunner.class)
public class PageModelControllerTest {
#Mock
private PageModelService pageModelService;
#InjectMocks
private PageModelController pageModelController;
private WebTestClient client;
#Before
public void setup() {
client = WebTestClient.bindToController(pageModelController).build();
}
}
I can't create the client, it tells me it can't autowire pageModelService
any idea

Spring restful service test case fail HTTP status is 500

I want to implement test case for spring restful web services which return a json
MY controller test class is :
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = {WebAppContext.class,JpaTestConfiguration.class
})
#WebAppConfiguration
public class DominProfileRestControllerTest {
private MockMvc mockMvc;
#Autowired
private WebApplicationContext webApplicationContext;
private MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(),
MediaType.APPLICATION_JSON.getSubtype(),
Charset.forName("utf8"));
#Before
public void setUp() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
#Test
public void testGetDomainProfile() throws Exception {
String profileId = domainProfile.getId().toString();
System.out.print("testing restful"+profileId);
mockMvc.perform(get("/service/domainprofile/get/{id}", profileId) )
.andExpect(status().isOk())
.andExpect(content().contentType(contentType))
.andExpect(jsonPath("$.city", is("Chandigrah")));
/* mockMvc.perform(get("/service/domainprofile/get/{id}",profileId).accept(MediaType.TEXT_PLAIN))
.andExpect(status().isOk())
.andExpect(content().contentType("text/plain;charset=ISO-8859-1"))
.andExpect(content().string("hello Prashant"));
*/
}
My Controller class Is :
#RestController
#RequestMapping("/service/domainprofile")
public class DominProfileRestController {
#Autowired
private JpaDomainProfileRepository jpaDomainProfileRepository;
#RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
public DomainProfileResource getDomainProfile(#PathVariable String id) {
JpaDomainProfile domainProfile = jpaDomainProfileRepository.findOne(Long.valueOf(id));
DomainProfileResource domainProfileResource = new DomainProfileResource();
System.out.println("domainProfile.getCity()*************" + domainProfile.getCity());
System.out.println("domainProfile.getAddress()*************" + domainProfile.getAddress());
domainProfileResource.setCity(domainProfile.getCity());
domainProfileResource.setAddress(domainProfile.getAddress());
// return new ResponseEntity<DomainProfileResource>(domainProfileResource, HttpStatus.OK);
return domainProfileResource;
// return domainProfile;
}
}
When I run test case I got An error while we got values in domainprofile.city and domainprofile.address.
Error Is :
java.lang.AssertionError: Status
Expected :200
Actual :500
It Is Working Fine When I return a plain text
can you do this
mockMvc.perform(get("/service/domainprofile/get/{id}", profileId) )
.andDo(print());
this will print the full response with exception , now if you see HttpMessageNotWritableException which was the issue I was facing , you should try to serialize your object using jackson and see if it works (spring internally uses Jackson ). For example , If any of your fields are null the Serialization will fail.