I am using PowerMockito and this is my test:
import com.PowerMockitoProduction;
import org.apache.commons.httpclient.HttpClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
#RunWith(PowerMockRunner.class)
#PrepareForTest(HttpClient.class)
public class PowerMockitoTest {
#Test(expected = UnsupportedOperationException.class)
public void test() throws Exception {
PowerMockito.whenNew(HttpClient.class).withNoArguments().thenThrow(new UnsupportedOperationException());
new PowerMockitoProduction().createClient();
}
}
This test is failing.
java.lang.AssertionError: Expected exception: java.lang.UnsupportedOperationException
Here's what PowerMockitoProduction does:
package com;
import org.apache.commons.httpclient.HttpClient;
public class PowerMockitoProduction {
public void createClient() {
HttpClient client = new HttpClient();
System.out.println(client);
}
}
I expect this code to create a mock HttpClient based on this line in my test:
PowerMockito.whenNew(HttpClient.class).withNoArguments().thenThrow(new UnsupportedOperationException());
But it doesn't seem to be effecting my production code. What am I doing wrong?
I figured out what I was doing wrong. I need to change:
#PrepareForTest(HttpClient.class)
to
#PrepareForTest(PowerMockitoProduction.class)
Related
I've been trying to transfer my restassured tests using testng over to cucumber and I've almost cracked it however the assertion has thrown me a little bit. This issue I have is the body in my assertion is throwing this error.
java: cannot find symbol
symbol: method body(java.lang.String,org.hamcrest.Matcher<java.lang.String>)
location: class stepdefs.articlesCucumberTests
Here is my current working tests.
import static io.restassured.RestAssured.*;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
import static org.hamcrest.Matchers.*;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.path.json.JsonPath;
import org.testng.annotations.Test;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
#SuppressWarnings("unchecked")
public class articlesTestNg extends enablers {
//Checks articles individual ID's.
#Test(dataProvider = "getId")
public void TestAllArticles(String articlesId) {
given().
given().log().all().and().
pathParam("id", articlesId).
when().
get(singleArticles).
then().
assertThat().
statusCode(200).
body(("id"), equalTo(articlesId));
}
//Checks the whole content of the json file using an expected outcome in the project structure.
#Test
public void GetArticlesJson() {
JsonPath expectedJson = new JsonPath(new File(pathJson));
given().
when().
get(allArticles).
then().
assertThat().
statusCode(200).
and().
body("", hasItem(expectedJson.getMap("")));
}
Here is my so far attempt at the cucmber tests in the I will receive an individual article the body is throwing the error. Is there a better way to do this?
package stepdefs;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import org.junit.jupiter.api.Assertions;
import org.testng.Assert;
import org.testng.annotations.Test;
import skySportsPages.enablers;
import static io.restassured.RestAssured.baseURI;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
public class articlesCucumberTests extends enablers {
private Response response;
#Test
#Given("I have a set of articles containing individual ID's")
public void i_have_a_set_of_articles_containing_individual_id_s() {
RestAssured.baseURI = singleArticles;
System.out.println(baseURI);
}
#Test(dataProvider = "getId")
#When("I get an the article ID")
public void i_get_an_the_article_id(String articlesId) {
given().
given().log().all().and().
pathParam("id", articlesId).
when().
get(singleArticles);
}
#Test
#Then("I will receive an individual article")
public void i_will_receive_an_individual_article(String articlesId) {
Assert.assertEquals(body(("id"), equalTo(articlesId)));
}
#Test
#Given("I have a set of articles")
public void i_have_a_set_of_articles(String articlesId) {
}
#Test
#When("I get the list of articles")
public void i_get_the_list_of_articles() {
}
#Test
#Then("It will match the json file")
public void it_will_match_the_json_file() {
}
}
No, I think we don't use #Test annotation in cucumber step. You should check out at toolqa for more tutorials.
Error is here because Assert.assertEquals should have two parameters, in your case you have only one body(("id"), equalTo(articlesId)) that may return boolean, so check first what you have just performing:
#Test
#Then("I will receive an individual article")
public void i_will_receive_an_individual_article(String articlesId) {
body(("id"), equalTo(articlesId));
}
And then try to change to:
Assert.assertTrue(body(("id"), equalTo(articlesId)));
I have below code to retry the request based on response code.
public class Sample {
public static HttpClient getInstance() {
HttpClientBuilder builder = HttpClients.custom();
builder.setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() {
int waitPeriod = 200;
#Override
public boolean retryRequest(final HttpResponse response, final int executionCount,
final HttpContext context) {
int statusCode = response.getStatusLine().getStatusCode();
return ((statusCode == 429)&& (executionCount < 3));
}
#Override
public long getRetryInterval() {
return waitPeriod;
}
});
return builder.build();
}
}
While I am writing the unit tests for this getInstance method the overridden methods (retryRequest, getRetryInterval) are not getting covered. How can I write the unit tests to get coverage for these methods as well.
By googling I found we can use ArgumentCaptor.
I have tried the below code, but it does not work.
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.verify;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ServiceUnavailableRetryStrategy;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HttpContext;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
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;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
#WebAppConfiguration
#RunWith(PowerMockRunner.class)
#PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "classpath:context.xml"})
#PrepareForTest({ HttpClients.class, Sample.class})
public class Sample {
#Mock
HttpClientBuilder clientBuilderMock;
#Mock
CloseableHttpClient clientMock;
#Mock
HttpResponse responseMock;
#Mock
HttpContext contextMock;
#Mock
StatusLine statusLineMock;
#Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
PowerMockito.mockStatic(HttpClients.class);
}
#Test
public void test() throws Exception {
when(HttpClients.custom()).thenReturn(clientBuilderMock);
when(clientBuilderMock.build()).thenReturn(clientMock);
when(responseMock.getStatusLine()).thenReturn(statusLineMock);
when(statusLineMock.getStatusCode()).thenReturn(429);
Sample.getInstance();
ArgumentCaptor<ServiceUnavailableRetryStrategy> argumentCaptor = ArgumentCaptor.forClass(ServiceUnavailableRetryStrategy.class);
verify(clientBuilderMock).setServiceUnavailableRetryStrategy(argumentCaptor.capture());
ServiceUnavailableRetryStrategy retryStrategy = argumentCaptor.getValue();
retryStrategy.retryRequest(responseMock, 3, contextMock);
}
}
argumentCaptor.capture() is always giving me null.I am getting like
org.mockito.exceptions.base.MockitoException:
No argument value was captured!
You might have forgotten to use argument.capture() in verify()...
...or you used capture() in stubbing but stubbed method was not called.
Can anyone help me on this. I would like to test the retryRequest method functionality.
Edit: rephrased the answer to make it easier to read.
Classes that are supposed to be handeled by PowerMockito need to be
declared in the #PrepareForTest annotation.
If annotations are used to create the mocks all annotated classes which are not declared in the #PrepareForTest annotation, are created by Mockito.
If annotations are used to create the mocks and MockitoAnnotations.initMocks(this); is called,
this apparently causes the declaration to be overriden and all mocks are created by Mockito instead.
(Source: https://groups.google.com/forum/#!topic/powermock/yPBey4hr7IU)
Mockito can not handle static or final methods. The mocking operation might fail silently.
The root of your problem is that HttpClientBuilder#setServiceUnavailableRetryStrategy is a
final method and therefore can not be handeled by Mockito.
The solution is that the Mock of HttpClientBulder has to be handeled by PowerMockito.
In accordance with 1. it needs to be declared in the #PrepareForTest annotation.
#PrepareForTest({ HttpClients.class, HttpClientBuilder.class, Sample.class})
If you want to use Annotations to create the mocks, you must not call
MockitoAnnotations.initMocks(this);
(see 2. / I verified this issue with the latest powermockito versions (1.7.4 / 2.0.2))
Else you have to create the mock manually.
HttpClientBuilder clientBuilderMock = PowerMockito.mock(HttpClientBuilder.class);
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 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?