Integration test for RESTful Web Service - java

This is my integration test controller class. Method get all team and there was a problem with compilation:
#SpringJUnitWebConfig(classes = CrewApplication.class)
public class Team_Controller_Integration_Test {
private MockMvc mockMvc;
#Autowired
private WebApplicationContext webApplicationContext;
#Before
public void setup() throws Exception
{
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
MockitoAnnotations.initMocks(this);
}
#Test
void getAccount() throws Exception {
this.mockMvc.perform(get("/teams")
.accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$version").value(null))
.andExpect(jsonPath("$name").value("Apacze"))
.andExpect(jsonPath("$createOn").value(null))
.andExpect(jsonPath("modifiedOn").value(null))
.andExpect(jsonPath("$description").value("grupa programistow"))
.andExpect(jsonPath("$city").value("Włocławek"))
.andExpect(jsonPath("$headcount").value(null));
}
}
This is my error:
java.lang.NullPointerException
On the other hand I create test for Db adn I have problem becouse after add mock elements to db they return null:
#RunWith(SpringRunner.class)
#DataJpaTest
public class Team_database_integration_test {
#MockBean
private TeamRepository teamRepository;
#Autowired
private TestEntityManager testEntityManager;
#Test
public void testDb(){
Team team = new Team(1L,"teamName","teamDescription","krakow",7);
testEntityManager.persist(team);
testEntityManager.flush();
System.out.println(team);
}
}

Add this dependency declaration to test case
#Autowired
private WebApplicationContext webApplicationContext;
and correct the initialization
#Before
public void setup() throws Exception
{
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
MockitoAnnotations.initMocks(this);
}
try changing to this signature,i think content type is by default -json.Try without assertions first then add assertions for validations!
MvcResult CDTO = this.mockMvc.perform(get("/plan/1"))
.andExpect(status().isOk())
.andReturn();

Related

java.lang.IllegalStateException: Failed to load ApplicationContext While running gradle clean build

I have 2 Test files but whenever I try to run gradle clean build,
I getting java.lang.IllegalStateException: Failed to load ApplicationContext, when i remove the #AutoConfigureMockMvc, then i get an error Could not autowire. No beans of 'MockMvc' type found.
1st File JobTest
#RunWith(SpringRunner.class)
#SpringBootTest
#AutoConfigureMockMvc
public class JobTest {
#Autowired
private WebApplicationContext applicationContext;
#Autowired
private MockMvc mockMvc;
#MockBean
private JobService jobService;
private static final String URI = "/testJob/";
#BeforeEach
void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(applicationContext).build();
}
private final UUID jobId = UUID.fromString("d35089c0-8ca8-4a9d-8932-8464e9a0736c");
#Test
public void testRequestJob() throws Exception {
//create a request object
RequestBuilder requestBuilder = MockMvcRequestBuilders.post(URI)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.ALL)
.content("testRequestString");
when(jobService.neededJob(anyString()).thenReturn(mockJob);
ResultActions perform = mockMvc.perform(requestBuilder);
assertEquals(HttpStatus.OK.value(), perform.andReturn().getResponse().getStatus());
//perform the request and get the response
perform.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.data.jobId").exists());
}
}
2nd File EmployerTest
#RunWith(SpringRunner.class)
#SpringBootTest
#AutoConfigureMockMvc
public class ShiftControllerTest {
#Autowired
private WebApplicationContext applicationContext;
#Autowired
private MockMvc mockMvc;
#MockBean
private EmployerService employerService;
#BeforeEach
void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(applicationContext).build();
}
private final UUID jobId = UUID.fromString("d35089c0-8ca8-4a9d-8932-8464e9a0736c");
private static final String URI = "/employer/";
#Test
public void testEmployer() throws Exception {
RequestBuilder requestBuilder = MockMvcRequestBuilders.get(URI + jobId)
.accept(MediaType.ALL);
when(employerService.getEmployer(jobId)).thenReturn(mockEmployer);
ResultActions perform = mockMvc.perform(requestBuilder);
assertEquals(HttpStatus.OK.value(), perform.andReturn().getResponse().getStatus());
}
}
If I comment one file and then try to run gradle clean build it works properly, any suggestion will be appreciated.
In the code that you have posted you don't seem to use the WebApplicationContext for anything else apart from creating a MockMvc object which you have already created anyway by virtue of the #Autowired annotation. If you don't need it for anything else try just removing the WebApplicationContext. For example:
#RunWith(SpringRunner.class)
#SpringBootTest
#AutoConfigureMockMvc
public class JobTest {
// #Autowired
// private WebApplicationContext applicationContext;
#Autowired
private MockMvc mockMvc;
#MockBean
private JobService jobService;
private static final String URI = "/testJob/";
// #BeforeEach
// void setup() {
// this.mockMvc = MockMvcBuilders.webAppContextSetup(applicationContext).build();
// }
private final UUID jobId = UUID.fromString("d35089c0-8ca8-4a9d-8932-8464e9a0736c");
#Test
public void testRequestJob() throws Exception {
//create a request object
RequestBuilder requestBuilder = MockMvcRequestBuilders.post(URI)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.ALL)
.content("testRequestString");
when(jobService.neededJob(anyString()).thenReturn(mockJob);
ResultActions perform = mockMvc.perform(requestBuilder);
assertEquals(HttpStatus.OK.value(), perform.andReturn().getResponse().getStatus());
//perform the request and get the response
perform.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.data.jobId").exists());
}
}

MockMvc Spring Boot springSecuirtyChainCannotBeNull issue

Can someone point me to what could be wrong in below code. It is a boot spring 2.6.7 application. When test profile is running, it throws error for all tests like below.
java.lang.IllegalStateException: springSecurityFilterChain cannot be null. Ensure a Bean with the name springSecurityFilterChain implementing Filter is present or inject the Filter to be used
#AutoConfigureMockMvc
#SpringBootTest(classes = some.class)
#ActiveProfiles("test")
public class someTest {
#Autowired
private MockMvc mvc;
#Autowired
private WebApplicationContext webAppContext;
#MockBean
private SomeBean someBean;
#SpyBean
private SomeSpyBean someSpyBean;
#BeforeEach
public void setup() {
mvc = MockMvcBuilders
.webAppContextSetup(webAppContext)
.apply(springSecurity())
.build();
}
#Test
public void SomeTest1() throws Exception {
String text = "text1";
when(someBean.findStuff(text).thenReturn(Optional.of(new Thingie()));
mvc.perform(multipart("/api/somepath/")
.andExpect(status().isNotFound());
verify(someSpyBean).doStuff();
}
#Test
public void SomeTest2() throws Exception {
String text = "text2";
when(someBean.findStuff(text).thenReturn(Optional.of(new Thingie()));
mvc.perform(multipart("/api/somepath/")
.andExpect(status().isFound());
verify(someSpyBean).doStuff();
}
}

I get this error during my mock test: Failed to load ApplicationContext

I'm getting this error while trying run a controller test
This is the full error:
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bookController':
Unsatisfied dependency expressed through field
'bookService'; nested exception is
This is the test:
#Test
public void bookRemoveTest() throws Exception {
securityService.autologin("admin", "admin");
Book book = new Book();
book.setId(1L);
bookService.findOne(1L);
expect(bookService.findOne(anyLong())).andReturn(book);
replay(bookService);
MvcResult result = mockMvc
.perform(post("/book/remove")
.accept(MediaType.TEXT_HTML)
.contentType(MediaType.TEXT_HTML))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.TEXT_HTML))
.andReturn();
}
And this is the controller I'm trying to test:
#RequestMapping(value = "/remove", method = RequestMethod.POST)
public String remove(
#ModelAttribute( "id" ) String id, Model model
) {
bookService.removeOne(Long.parseLong(id.substring(8)));
List<Book> bookList = bookService.findAll();
model.addAttribute("bookList", bookList);
return "redirect:/book/bookList";
}
Personally I think the problem is coming from here:
#Before
public void setUp() {
bookService = createMock(BookService.class);
ReflectionTestUtils.setField(bookController, "bookService", bookService);
userRepository= createMock(UserRepository.class);
ReflectionTestUtils.setField(bookController, "userRepository", userRepository);
mockMvc = standaloneSetup(bookController)
.setMessageConverters(new ByteArrayHttpMessageConverter())
.build();
}
Here I am trying to perform mock injections so I can use my service in mock tests
your test class should use #InjectMock and #Mock to mock both controller and service.
public class BookControllerTest {
#InjectMocks
BookController controller;
#Mock
BookService bookService; // will be inject to BookController
MockMvc mockMvc;
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
mockMvc = standaloneSetup(controller)
.setSingleView(mockView)
.build();
}
#Test
public void bookRemoveTest() throws Exception {
...
}
}
For more detail : PROPERLY TESTING SPRING MVC CONTROLLERS

How to properly test a Spring Boot using Mockito

I never did a test and decided I would do my first.
I am using Spring Boot and by default the layout is as follows: https://zapodaj.net/c8b65f1644e95.png.html
The file that is created on startup looks like this
#RunWith(SpringRunner.class)
#SpringBootTest
public class RestWebServicesApplicationTests {
#Test
public void contextLoads() {
}
}
I do not change anything here, because I do not need it.
By contrast, I created a new class
public class CheckUserDataRestControllerTest {
#Mock
private UserService userService;
#InjectMocks
private CheckUserDataRestController checkUserDataRestController;
private MockMvc mockMvc;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(checkUserDataRestController).build();
}
#Test
public void textExistsUsername() throws Exception {
mockMvc
.perform(get("/checkUsernameAtRegistering")
.param("username", "jonki97"))
.andExpect(status().isOk());
}
}
To test the controller method, which should return the status OK.
#GetMapping("/checkUsernameAtRegistering")
public HttpEntity<Boolean> checkUsernameAtRegistering(#RequestParam String username) {
return ResponseEntity.ok().body(!userService.existsByUsername(username));
}
However, during the test, he throws me out
java.lang.AssertionError: Status
Expected :200
Actual :404
<Click to see difference>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:54)
...
This is the tested controller: https://pastebin.com/MWW9YwiH
I did not make any special configurations because I did not find out that I needed to do something.
The error 404 means the Mock does not recognize your endpoint to test. The end point should be:
#Test
public void textExistsUsername() throws Exception {
mockMvc
.perform(get("/checkUserData/checkUsernameAtRegistering")
.param("username", "jonki97"))
.andExpect(status().isOk());
}
Hope this help.

Mockito - Mock autowired repository in service

I'm triying to write a test from a controller.
The controller call a service who call an autowired repository.
Here is my class right now
#RunWith(MockitoJUnitRunner.class)
public class AdminDestinationControllerTest {
private final PTUser user = new PTUser();
private MockMvc mockMvc;
#InjectMocks
private AdminDestinationController adminDestinationController;
#Mock private RoutingDestinationServiceImpl routingDestinationService;
#Mock private PTRoutingDestinationRepository destinationRepository;
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(adminDestinationController).build();
}
#Test
public void setCost_UnknownCode() throws Exception {
when(routingDestinationService.setCost(Mockito.anyString(), Mockito.any())).thenCallRealMethod();
when(destinationRepository.setCost(Mockito.anyString(), Mockito.any())).thenReturn(Optional.empty());
mockMvc.perform(post("/admin/destinations/cost").content("{\"code\":\"99999\", \"cost\":\"2\"}").contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isNotFound());
}
}
But in the service, the repository is null.
Any ideas of how I could do ?
Thank you

Categories