I am trying to create a test for a login page using JUnit where I need to mock out dev controller.
As I used a HttpServlet in my dev environment, for testing environment it is asking for httprequest...
I went for Mock request where my file is not getting where I'm using a controller not a servlet.
Can anyone help me on this?
Below is my JUnit Controller
package com.atoc.test.controller;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.when;
import com.atoc.test.DAO.UserTestDAO;
import com.atoc.test.service.UserTestService;
import com.bpa.qaproduct.controller.UserController;
import com.bpa.qaproduct.entity.User;
import com.bpa.qaproduct.service.UserService;
import org.apache.commons.io.FileUtils;
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextConfiguration(locations = { "classpath:testApplicationContext.xml" })
public class UserControllerTest{
#Mock
private UserService userService;
#Mock
private HttpServletRequest request;
#Mock
private HttpServletResponse response;
#InjectMocks
private UserController userController;
private MockMvc mockMvc;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(userController).build();
}
#Test
public void testviewUserrList() throws Exception {
User user = new User();
//int value = null;
when(userService.getUserFilterCount(user)).thenReturn(20);
//mockMvc.perform(get("/todo/"));
mockMvc.perform(get("/user/viewUserList")).andExpect(status().isOk());
}
#Test
public void testloginVerification() throws Exception
{
User user = new User();
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
when(request.getParameter("userName")).thenReturn("me");
when(request.getParameter("password")).thenReturn("secret");
mockMvc.perform(post("/user/loginVerification"))
.andExpect(status().isOk());
System.out.println("***********"+request.getParameter("userName"));
}
}
The test case does not pass and httprequest is not passing values.
So I'm getting a NullPointerException in my running environment
I mocked out the request and response methods but I'm still getting the same error.
Passing value is not null
I'm giving some values there
setting time might be the problem
I didn't extend any Mockito in main class where I'm using inner methods
You have to provide request parameters to mockmvc instead of a request object.
#Test
public void testloginVerification() throws Exception {
User user = new User();
mockMvc.perform(post("/user/loginVerification")
.param("userName", "me")
.param("password", "secret"))
.andExpect(status().isOk());
}
Also the User object is not interacting with the other code of your test. I think you're doing something completely wrong. Can you add the code of the UserController?
Related
package com.azry.ptm.api;
import com.azry.ptm.api.model.account.AccountDTO;
import com.azry.ptm.domain.account.Account;
import com.azry.ptm.server.services.AccountService;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpStatus;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.test.web.servlet.MockMvc;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.ArgumentMatchers.anyLong;
#AutoConfigureMockMvc
#SpringBootTest
public class AccountControllerImplTest {
#Autowired
private MockMvc mockMvc;
#MockBean
public AccountService accountService;
#Test
public void test() throws Exception {
final long entityNo = 10;
Account expectedAccount = Account.builder()
.entityNo(entityNo)
.build();
Mockito.when(accountService.getAccountById(anyLong())).thenReturn(Optional.of(expectedAccount));
MockHttpServletResponse response = mockMvc.perform(ControllerTestHelper.makeGetRequest("account/", String.valueOf(entityNo)))
.andReturn()
.getResponse();
AccountDTO responseAccount = ControllerTestHelper.toObject(response.getContentAsString(), AccountDTO.class);
assertEquals(HttpStatus.OK.value(), response.getStatus());
assertNotNull(responseAccount);
}
}
Here is my mockMvc test. it works only when the controller is in the same module es test, otherwise, when I split the project it returns a 404 error code as no endpoint was found.
has anybody experience using mockMvc in a multi-module spring-boot app?
solved using #WebMvcTest annotation
#WebMvcTest(AccountControllerImpl.class)
I am using spring boot 1.5.x for application. Database is MONGO
Using MongoRepository for crud operations.
Earlier in our project we got dedicated test database instance so we have added mongodb properties of test db in src\test\resources\application.properties.
Now we dont have test db so we want to use embedded/fake db to test our classes Controller/Services/Repository etc..
Options are - embeded mongodb like flapdoodle and fongo
I tried 1 of solution de.flapdoodle.embed.mongo from SO question to use flapdoodle
de.flapdoodle.embed.mongo trying to download zip outside network : unable-to-download-embedded-mongodb-behind-proxy-using-automatic-configuration
I tried fakemongo but its not working for unit and integration testing of controller. Its picking mongo database details of test db using application.properties present in test/resources
pom.xml
<dependency>
<groupId>com.github.fakemongo</groupId>
<artifactId>fongo</artifactId>
<version>${fongo.version}</version>
<!--<scope>test</scope> -->// not working, if removed it says cannot find mongo
</dependency>
<dependency>
<groupId>com.lordofthejars</groupId>
<artifactId>nosqlunit-mongodb</artifactId>
<version>0.7.6</version>
<scope>test</scope>
</dependency>
FakeMongo Configuration
package com.myapp.config;
import com.github.fakemongo.Fongo;
import com.mongodb.MongoClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoConfiguration;
#Configuration
#EnableMongoRepositories
public class FakeMongo extends AbstractMongoConfiguration {
#Override
protected String getDatabaseName() {
return "mockDB";
}
#Bean
public MongoClient mongo() {
Fongo fongo = new Fongo("mockDB");
return fongo.getMongo();
}
}
TestFakeMongo It works. Test executed properly - Reference http://springboot.gluecoders.com/testing-mongodb-springdata.html
package com.myapp.config;
import com.myapp.domain.entitlement.User;
import com.myapp.repository.UserRepository;
import com.lordofthejars.nosqlunit.annotation.UsingDataSet;
import com.lordofthejars.nosqlunit.core.LoadStrategyEnum;
import com.lordofthejars.nosqlunit.mongodb.MongoDbRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import static com.lordofthejars.nosqlunit.mongodb.MongoDbRule.MongoDbRuleBuilder.newMongoDbRule;
import static org.junit.Assert.assertTrue;
#RunWith(SpringRunner.class)
#Import(value = {FakeMongo.class})
public class TestFakeMongo {
#Autowired
private ApplicationContext applicationContext;
#Rule
public MongoDbRule embeddedMongoDbRule = newMongoDbRule().defaultSpringMongoDb("mockDB");
#MockBean
private UserRepository userRepository;
#Test
#UsingDataSet(loadStrategy = LoadStrategyEnum.DELETE_ALL)
public void getAllUsers_NoUsers() {
List<User> users = userRepository.findAll();
assertTrue("users list should be empty", users.isEmpty());
}
}
UserRepositoryTest - Unit testing for Repository also working using fongo Reference - http://dontpanic.42.nl/2015/02/in-memory-mongodb-for-unit-and.html
package com.myapp.repository;
import com.myapp.config.SpringUnitTest;
import com.myapp.domain.User;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
public class UserRepositoryTest extends SpringUnitTest {
#Autowired
private UserRepository userRepository;
#Before
public void setup() {
importJSON("user", "user/user.json");
}
#Test
//#UsingDataSet(loadStrategy = LoadStrategyEnum.CLEAN_INSERT, locations = "/json-data/user/user.json") // test/resources/..
public void findUser_should_return_user() {
User user = userRepository.findByXYZId("XX12345");
assertNotNull(user);
}
#Test
public void findUser_should_return_null() {
User user = userRepository.findByXYZId("XX99999");
assertNull(user);
}
#Test
public void deleteUser_should_return_null() {
userRepository.delete("XX12345");
User user = userRepository.findByXYZId("XX12345");
assertNull(user);
}
#Test
public void saveUser_should_return_user() {
User user = new User();
user.setXYZId("XX12345");
user.setAck(true);
List<DateTime> dateTimeList = new ArrayList<>();
dateTimeList.add(DateTime.now(DateTimeZone.UTC));
user.setAckOn(dateTimeList);
User dbUser = userRepository.save(user);
assertEquals(user, dbUser);
}
#Test
public void findAllUser_should_return_users() {
List<User> userList = userRepository.findAll();
assertEquals(1, userList.size());
}
}
Controller level testing not working.. Reference- https://www.paradigmadigital.com/dev/tests-integrados-spring-boot-fongo/
UserControllerTest failed java.lang.IllegalStateException: Failed to load ApplicationContext - At this point test mongo db details fetech instead of fongo test\resources\application.properties test server db details are loading
package com.myapp.config;
package com.myapp.controllers;
import com.myapp.config.FakeMongo;
import com.myapp.services.persistance.UserService;
import com.lordofthejars.nosqlunit.mongodb.MongoDbRule;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
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.Import;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultMatcher;
import static com.lordofthejars.nosqlunit.mongodb.MongoDbRule.MongoDbRuleBuilder.newMongoDbRule;
import static org.hamcrest.CoreMatchers.containsString;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
#ActiveProfiles("it")
#RunWith(SpringRunner.class)
#SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
classes = Application.class
)
#Import(value = {FakeMongo.class})
#AutoConfigureMockMvc
#TestPropertySource(locations = "classpath:application-it.properties")
public class UserControllerTest {
#Rule
public MongoDbRule embeddedMongoDbRule = newMongoDbRule().defaultSpringMongoDb("mockDB");
#Autowired
private MockMvc mockMvc;
#MockBean
private UserService service;
#Before
public void setUp() throws Exception {
}
#Test
public void deleteUser() throws Exception {
Mockito.when(this.service.deleteUser(Mockito.anyString())).thenReturn(true);
this.mockMvc.perform(delete("/User")).andDo(print()).andExpect(status().isOk())
.andExpect((ResultMatcher) content().string(containsString("true")));
}
}
UserControllerTest Not working, failing with error java.lang.IllegalStateException: Failed to load ApplicationContext as its tries to connect to test instance of mongo database using application.properties present in test/resources
Appreciate working example to use fakemongo while running Integration test for Controller level
What changes, I need to do in code level(Controller class or any other class) or application.properties of test\resources ?
I am developing simple Rest API app and trying to test it using this tutorial: http://memorynotfound.com/unit-test-spring-mvc-rest-service-junit-mockito/
I have implemented entire test_get_all_success unit test using my working Rest API (written in Spring MVC). Unfortunately test cannot run because of following issue.
Here is entire test file:
import java.util.Arrays;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import static org.hamcrest.Matchers.*;
import org.junit.Before;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import static org.mockito.Mockito.*;
import org.mockito.MockitoAnnotations;
import org.springframework.http.MediaType;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes={MyConfigClass.class})
#WebAppConfiguration
public class ClientTest {
private MockMvc mockMvc;
#Mock
private ClientManagerImpl clientManager;
#InjectMocks
private ClientController clientController;
#Before
public void init(){
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders
.standaloneSetup(clientController)
.build();
}
#Test
public void findAll_ClientsFound_ShouldReturnFoundClients() throws Exception {
Client a = ...;
Client b = ...;
when(clientManager.getClients()).thenReturn(Arrays.asList(a, b));
mockMvc.perform(get("/clients"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$", hasSize(2)));
verify(clientManager, times(1)).getClients();
verifyNoMoreInteractions(clientManager);
}
}
NetBeans shows error in this line:
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
incompatible types: RequestMatcher cannot be converted to ResultMatcher
Test cannot run because of this error. When I delete this line everything works fine and test is passed.
What am I doing wrong?
The following static import causes the conflict:
import static org.springframework.test.web.client.match.MockRestRequestMatchers.content;
MockRestRequestMatchers class is used for client-side REST testing using MockRestServiceServer, but you are testing here MVC application controllers.
I am trying to mock private method inside singleton bean. Test class looks like:
import static org.mockito.Matchers.anyObject;
import static org.mockito.Mockito.when;
import java.util.Hashtable;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
#RunWith(PowerMockRunner.class)
#PrepareForTest(SampleBean.class)
public class SampleBeanTest{
#InjectMocks
private SampleBean sampleBean = new SampleBean();
/**
* Sets the up.
* #throws Exception the exception
*/
#Before
public final void setUp() throws Exception {
//MockitoAnnotations.initMocks(SampleBean);
PowerMockito.doReturn("response").when(sampleBean, "privateMethod", anyObject(), DUMMY_QUEUE);
}
#Test
public void testGetData() throws Exception {
sampleBean.publicMethod();
}
}
When I run test, I get exception as:
java.lang.NullPointerException: null
at org.powermock.api.mockito.internal.expectation.PowerMockitoStubberImpl.addAnswersForStubbing(PowerMockitoStubberImpl.java:68)
at org.powermock.api.mockito.internal.expectation.PowerMockitoStubberImpl.prepareForStubbing(PowerMockitoStubberImpl.java:123)
at org.powermock.api.mockito.internal.expectation.PowerMockitoStubberImpl.when(PowerMockitoStubberImpl.java:91)
at com.temp.SampleBeanTest.setUp(SampleBeanTest.java:30)
I found out that PowerMock returns null at line:
MockitoMethodInvocationControl invocationControl = (MockitoMethodInvocationControl) MockRepository.getInstanceMethodInvocationControl(mock);
I am not sure what is the reason behind this weird behavior. Please let me know, if you have any idea.
It looks like sampleBean is null.
You need the MockitoAnnotations.initMocks call that is commented-out, but like this:
MockitoAnnotations.initMocks(this);
Or, doing it manually:
sampleBean = mock(SampleBean.class);
I'm trying to run a test for testing a Spring MVC controller. The test compile and runs, but my problem is that I got a PageNotFound warning:
WARN PageNotFound - No mapping found for HTTP request with URI [/] in DispatcherServlet with name ''
My really simple test as follows:
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextConfiguration({
"classpath*:/WEB-INF/applicationContext.xml",
"classpath*:/WEB-INF/serviceContext.xml"
})
public class FrontPageControllerTest {
#Autowired
private WebApplicationContext ctx;
private MockMvc mockMvc;
#Before
public void init() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.ctx).build();
}
#Test
public void frontPageController() throws Exception {
this.mockMvc.perform(get("/"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(view().name("searchfrontpage"));
}
}
I'm 100% sure that my webapp maps to the frontpage at "/" and that the name on the view is "searchfrontpage".
Please help!
Another easier way to solve the issue is to change init to this :
mockMvc = MockMvcBuilders.standaloneSetup(new FrontPageController()).build();
My ContextConfiguration was wrong. Correct was:
#ContextConfiguration({
"file:src/main/webapp/WEB-INF/applicationContext.xml",
"file:src/main/webapp/WEB-INF/serviceContext.xml"
})
Now everything works fine.