Hi I have the following test and I cannot make it work, its giving NullPointerException:
Method to test :
private ResponseEntity getDefaultCart(HttpEntity<String> request, String zoomQuery) {
LOG.info("Get user's default cart with zoom query" + zoomQuery);
String defaultCartUrl = cortexApiUrl + Constants.CARTS + scope + Constants.DEFAULT + Constants.ZOOM + zoomQuery;
return baseRepository.getCall(defaultCartUrl, request);
}
Junit of this method:
#Test
public void testUpdateCart() {
MockitoAnnotations.initMocks(this);
cortexRepository= new CortexRepositoryImpl("https://abc.juy", "ocean", baseRepositoryImpl);
Mockito.when(baseRepositoryImpl.createRequestHeaders("guestId")).thenReturn(httpHeaders);
JSONObject orderDetails = createCortexCreateOrderObject("cortexCreateOrderResponse.json");
ResponseEntity<JSONObject> entity=new ResponseEntity<JSONObject>(orderDetails,HttpStatus.ACCEPTED);
HttpEntity<String> request = new HttpEntity<String>(httpHeaders);
Mockito.when(baseRepositoryImpl.getCall("http://www.abc.hyh", request)).thenReturn(entity);
cortexRepository.updateCart(updateCartRequest);
}
Method getDefaultCart is calling from updateCart method.The object orderDetails is filling correctly.
NUllPointer is giving on line : baseRepository.getCall(defaultCartUrl, request).
Any suggestion ??
I think that the instance of BaseRepositoryImpl being used when you call baseRepository.getCall(defaultCartUrl, request); is not the same instance being passed to new CortexRepositoryImpl("https://abc.juy", "ocean", baseRepositoryImpl);.
So make sure that you are not creating a new instance of it in CortexRepositoryImpl and are in fact using the object passed into the constructor.
I can't be sure without the source of CortexRepositoryImpl but this seems like the most likely issue.
Related
I m new to Mockito and trying to mock the webservice responses, I did tried mocking at some extent few Objects got worked, But the end mocked WebResponse is always returning null.
Service Method i am going to test:getWebResponse Method
public WebResponse getWebResponse(String crmNumber) throws JSONException, ExecutionException, WebException {
Map<String, String> HEADERS_POST = new HashMap<String, String>() {
{
put(WebUtil.HEADER_CONTENT, WebUtil.CONTENT_JSON);
put(WebUtil.HEADER_ACCEPT, WebUtil.CONTENT_JSON);
}
};
JSONObject requestJson = new JSONObject();
requestJson.put("crmNumber", crmNumber);
requestJson.put("application", "ABCD");
requestJson.put("feature", "DDDFL");
// Using internal web service becuase device authentication is done separately.
String url = CommonUtil.getServiceBaseUrl(true) + "/ett";
WebServiceClient client = WebServiceClientRegistry.getClient(ApacheCustom.class);
WebRequest webReq = new GenericWebRequest(WebRequestMethod.POST, url, HEADERS_POST, requestJson.toString());
// Till here i m getting all mocked object (client also Mocked) after this stament the webRes is returning null;
WebResponse webRes = client.doRequest(webReq);
return webRes;
}
And here the test Method:
#Test
public void getWebResponseTest() {
mockStatic(CommonUtil.class);
mockStatic(WebServiceClientRegistry.class);
this.webResponse = new GenericWebResponse(200, "", new HashMap(), "");
try {
Mockito.when(CommonUtil.getServiceBaseUrl(true)).thenReturn("https://stage.com/service");
WebRequest webReq = new GenericWebRequest(WebRequestMethod.POST, "https://stage.com/service", new HashMap(), "");
Mockito.when(WebServiceClientRegistry.getClient(ApacheCustom.class)).thenReturn(client);
Mockito.when(client.doRequest(webReq)).thenReturn(this.webResponse);
WebResponse wesponse = this.ServiceResponse.getWebResponse("Number");
Assert.assertEquals(wesponse.getStatusCode(), 200);
} catch (Exception e) {
Assert.fail();
}
}
But the getWebResonse method from Test class always returning null Response(Even Though it is mocked)
You mock client.doRequest as follows:
Mockito.when(client.doRequest(webReq)).thenReturn(this.webResponse);
but you create a new instance of WebRequest in your service under test.
You call doRequest with a different argument than recorded in your test.
Arguments are compared with equals.
Most likely WebRequest does not override equals, so recorded interaction is ignored and a default response (null) is rerurned.
I guess WebResuest may not be the code you own (you haven’t specified this in your question), so it may be impossible to override it.
Thus, you can use a different argument matcher.
You can use ArgumentMatchers.any() for good start, or implement a custom argument matcher.
testclass.java
#Test
public void testgetDictionaryValueListById() {
DictionaryValue dictionaryValue = new DictionaryValue();
dictionaryValue.setId(1);
dictionaryValue.setValueName("Test Dictionary Value");
dictionaryValue.setValueKey("12345678");
dictionaryValue.setStatus("Active");
dictionaryValue.setCreatedOn(new Date());
dictionaryValue.setUpdatedOn(new Date());
Mockito.when(dictionaryValueRepo.findById(1).get()).thenReturn(dictionaryValue);
assertThat(dictionaryService.getDictionaryValueListById(1)).isEqualTo(dictionaryValue);
}
Service.java
public DictionaryValue getDictionaryValueListById(int id) {
return dictionaryValueRepo.findById(id).get();
}
Repo.java
#Repository
public interface DictionaryValueRepo extends JpaRepository<DictionaryValue, Integer> {
}
I am getting no such value present again and again on executing test case in testclass.java. I don't know why? but when I am running my service method from the controller it is working as expected - fetching records from the database but not working in a test case.
Your test should be like this and please check out the naming. You need to Mock the step findId() befor the `get().
#InjectMocks
Service cut;
#Mock
DictionaryValueRepo dictionaryValueRepoMock;
// Can skipped by adding a #RunWith... on Testclass
#Before
public init() {
Mockito.initMocks(this);
}
#Test
public void testgetDictionaryValueListById() {
// Prepare Data
final int testId = 1;
DictionaryValue dictionaryValue = new DictionaryValue();
dictionaryValue.setId(testId);
dictionaryValue.setValueName("Test Dictionary Value");
dictionaryValue.setValueKey("12345678");
dictionaryValue.setStatus("Active");
dictionaryValue.setCreatedOn(new Date());
dictionaryValue.setUpdatedOn(new Date());
// config mocking
Mockito.when(dictionaryValueRepo.findById(testId)).thenReturn(<VALUE>);
Mockito.when(dictionaryValueRepo.findById(testId).get()).thenReturn(dictionaryValue);
// Call yout method for Testing
cut.getDictionaryValueListById(testId);
// verifies (if wanted) + assertions....
}
I concur with LenglBoy, so the right answer should be given to him.
The thing you need to be careful is what "VALUE" means in this line:
Mockito.when(dictionaryValueRepo.findById(testId)).thenReturn(VALUE);
The findById returns an Optional, so that is what you should build and pass to Mockito. Something like this:
Mockito.when(dictionaryValueRepo.findById(testId))
.thenReturn(Optional.ofNullable(dictionaryValue));
And for a scenario where the id does not exists in BD, passing Optional.empty() should be good enough.
During executing unit test the method is called 3 times. Each time it's called with different parameters. I want to verify, that on the last time method was called with corresponding paramets.
Please, help me.
My method :
private void doHandle(Updategram updategram)
throws FixtureNotFoundException, DatatypeConfigurationException {
BetSyncObject betSyncObject = transformer.transformer(updategram);
EventTreeCreation event = betSyncObject.eventTree;
if (!event.getEvent().isEmpty()) {
Event event2 = event.getEvent().get(0);
long timestamp =
updategram.getHeader().getTimeStampUtc().toGregorianCalendar().getTimeInMillis();
String sportName = event2.getSportcode();
String id = event2.getExtId();
publisher.publishEvent(PROVIDER_NAME, betSyncObject, sportName, id, timestamp);
} else {
LOGGER.info("Empty event tree : {}", betSyncObject);
}
}
Test:
#Test
public void testCountAndSetResultLine() throws Exception{
EventPublisher eventPublisher = Mockito.mock(EventPublisher.class);
BetgeniusService betgeniusService = new BetgeniusService();
BetSyncObject expectedBetSyncObj = transformer.transformer(updategram);
ExecutorService service = Executors.newFixedThreadPool(3);
handle(betgeniusService, updategramFixture, service);
Thread.sleep(50);
handle(betgeniusService, updategramMarketSet, service);
Thread.sleep(50);
handle(betgeniusService, updategramResult, service);
service.shutdown();
service.awaitTermination(20000, TimeUnit.MILLISECONDS);
betgeniusService.getExecutor().shutdown();
betgeniusService.getExecutor().awaitTermination(20000, TimeUnit.MILLISECONDS);
Mockito.verify(eventPublisher, Mockito.times(3)).publishEvent(Mockito.anyString(), Mockito.any(BetSyncObject.class),
Mockito.anyString(), Mockito.anyString(), Mockito.anyLong());
}
For this moment I am getting exception, because the publishEvent method is not called 3 times with exactly expectedBetSyncObj. It should be called with it only last time.
So, please tell how could I check that the publishEvent method was called with the expectedBetSyncObj object the last time.
I think you can achieve this with an ArgumentCaptor.
Use the ArgumentCaptor to get the arguments for all calls made and then later verify each one of them.
In your case you would verify that on the third call the argument (.get(2)) is the expected object.
So something like
ArgumentCaptor<BetSyncObject> betSyncObjectCaptor = ArgumentCaptor.forClass(BetSyncObject.class);
Mockito.verify(eventPublisher, Mockito.times(3)).publishEvent(Mockito.anyString(), betSyncObjectCaptor.capture(), Mockito.anyString(), Mockito.anyString(), Mockito.anyLong());
List<BetSyncObject> capturedBetSyncObject = betSyncObjectCaptor.getAllValues();
assertEquals(expectedBetSyncObj, capturedBetSyncObject.get(2));
I was trying to implement an Axis2 service that receives user requests and publishes them as events to a CEP using carbon databridge thrift (via 'org.wso2.carbon.databridge.agent.thrift.DataPublisher')
I followed the code sample provided in wso2cep-3.1.0/samples/producers/activity-monitor
please see the following code snippet
public class GatewayServiceSkeleton{
private static Logger logger = Logger.getLogger(GatewayServiceSkeleton.class);
public RequestResponse request(Request request)throws AgentException,
MalformedStreamDefinitionException,StreamDefinitionException,
DifferentStreamDefinitionAlreadyDefinedException,
MalformedURLException,AuthenticationException,DataBridgeException,
NoStreamDefinitionExistException,TransportException, SocketException,
org.wso2.carbon.databridge.commons.exception.AuthenticationException
{
final String GATEWAY_SERVICE_STREAM = "gateway.cep";
final String VERSION = "1.0.0";
final String PROTOCOL = "tcp://";
final String CEPHOST = "cep.gubnoi.com";
final String CEPPORT = "7611";
final String CEPUSERNAME = "admin";
final String CEPPASSWORD = "admin";
Object[] metadata = { request.getDeviceID(), request.getViewID()};
Object[] correlationdata = { request.getSessionID()};
Object[] payloaddata = {request.getBucket()};
KeyStoreUtil.setTrustStoreParams();
KeyStoreUtil.setKeyStoreParams();
DataPublisher dataPublisher = new DataPublisher(PROTOCOL + CEPHOST + ":" + CEPPORT, CEPUSERNAME, CEPPASSWORD);
//create event
Event event = new Event (GATEWAY_SERVICE_STREAM + ":" + VERSION, System.currentTimeMillis(), metadata, correlationdata, payloaddata);
//Publish event for a valid stream
dataPublisher.publish(event);
//stop
dataPublisher.stop();
RequestResponse response = new RequestResponse();
response.setSessionID(request.getSessionID());
response.setDeviceID(request.getDeviceID());
response.setViewID(request.getViewID());
response.setBucket(request.getBucket());
return response;
}
there is also a utility class that set the key store parameters as following
public class KeyStoreUtil {
static File filePath = new File("../../../repository/resources/security");
public static void setTrustStoreParams() {
String trustStore = filePath.getAbsolutePath();
System.setProperty("javax.net.ssl.trustStore", trustStore + "/client-truststore.jks");
System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
}
public static void setKeyStoreParams() {
String keyStore = filePath.getAbsolutePath();
System.setProperty("Security.KeyStore.Location", keyStore + "/wso2carbon.jks");
System.setProperty("Security.KeyStore.Password", "wso2carbon");
}
}
I uploaded the service into a wso2as-5.2.1, and called the service using SOAPUI
the request returned an error message "cannot borrow client for TCP"
I debug, and found out the problem might lies with the class 'KeyStoreUtil',
where the 'filePath' somehow retuned a 'null',
static File filePath = new File("../../../repository/resources/security");
and caused the failure on this line
DataPublisher dataPublisher = new DataPublisher(PROTOCOL + CEPHOST + ":" + CEPPORT, CEPUSERNAME, CEPPASSWORD);
I guess it could be a better idea if I use the value of "CARBON_HOME" to figure out the location of Key Store
so my question is :
How may I be able to get the value of 'CARBON_HOME' in the Java code?
that said. If you think a bit more:
the service will be called numerous time; whileas the 'setTrustStoreParams' and the 'setKeyStoreParams' will only be needed to executed once at the server/service initiate.
So, are there any even better ways to remove 'setTrustStoreParams' and 'setKeyStoreParams' out of the service code, or implement as configurable items?
Please advise
thanks
so my question is :
How may I be able to get the value of 'CARBON_HOME' in the Java code?
You should use the property carbon.home like following which will retrieve the WSO2 product's home directory.
System.getProperty("carbon.home");
I have see several questions here in Stackoverflow about out parameters in MOQ, my question is how fill this parameter: Lets to code:
[HttpPost]
public HttpResponseMessage Send(SmsMoRequest sms)
{
if (sms == null)
return Request.CreateResponse(HttpStatusCode.BadRequest);
SmsMoResponse response;
_messageService.Process(sms, out response);
return Request.CreateResponse(HttpStatusCode.Created, response.ToString());
}
I want to test this post:
[Test]
public void Should_Status_Be_Create_With_Valid_XML()
{
// Arrange
var messageServiceMoq = new Mock<IMessageService>();
SmsMoResponse response;
messageServiceMoq.Setup(mock => mock.Process(It.IsNotNull<SmsMoRequest>(), out response));
_kernel.Bind<IMessageService>().ToConstant(messageServiceMoq.Object);
var client = new HttpClient(_httpServer) { BaseAddress = new Uri(Url) };
// Act
using (var response = client.PostAsync(string.Format("Api/Messages/Send"), ValidContent()).Result)
{
// Asserts
response.IsSuccessStatusCode.Should().BeTrue();
response.StatusCode.Should().Be(HttpStatusCode.Created);
}
}
Problem
My response object in Send method (POST) is used in post response but the _messageService.Process is responsible to fill the response object.
In test method Should_Status_Be_Create_With_Valid_XML I mock _messageService.Process and response object is not fill ocorr error Null reference in Request.CreateResponse(HttpStatusCode.Created, response.ToString());
response is null!
Of course response is null, there's no code anywhere that would set it to anything (in your service method or your mock).
Since you're mocking the method that would usually fill it in, it's up to you to specify how it is set. You should fill in the object before calling Setup with what you expect to be the value when that method is called.
Also, see this question for more info.