Need a quick help. I am trying to write a test class and getting below error
"can not resolve the method .thenreturn(org.apache.kafka.clients.producer)
#Test
public void testPublishData_Success() throws java.lang.Exception {
when(GetPropValues.getPropValue(PublisherConstants.ATMID)).thenReturn("ATM");
when(GetPropValues.getPropValue(PublisherConstants.DATA_SOURCE)).thenReturn("PCE");
ReadAndWriteFiles mockFiles = Mockito.mock(ReadAndWriteFiles.class);
PowerMockito.whenNew(ReadAndWriteFiles.class).withNoArguments().thenReturn(mockFiles);
Mockito.when(mockFiles.getAllFiles()).thenReturn("someValue");
KafkaProducer mockProducer = Mockito.mock(KafkaProducer.class);
PowerMockito.whenNew(KafkaProducer.class).withAnyArguments().thenReturn(mockProducer);
producer.publishData(null, "Test", "Data1");
}
Powermockito is fine in returning ReadAndWriteFiles.class object but it is throwing an error for KafkaProducer.class. on line
PowerMockito.whenNew(KafkaProducer.class).withAnyArguments().thenReturn(mockProducer);
Is there any other way to for this work around? Any suggestion will be appreciated.
Note: KafkaProducer.class is in not a custom class but its inside from apache spark kafka libraries
Main code is as per below
KafkaProducer<String, String> producer = new KafkaProducer<String, String>(props);
InputData inputMessage;
try {
inputMessage = populateData(timeStamp, dataCategory, data, atmId, topic);
ReadAndWriteFiles readerWriter = new ReadAndWriteFiles();
File[] directory = readerWriter.getAllFiles();
if (directory != null && directory.length > 0) {
if (connectionSet && !publishingData) {
sendDataFromFiles(producer, directory);
publishingData = false;
}
} else {
producer.send(keyedMsg, new KafkaResponseHandler(inputMessage));
}
} catch (IOException e) {
}
I think the error is
KafkaProducer mockProducer = Mockito.mock(KafkaProducer.class);
PowerMockito.whenNew(ReadAndWriteFiles.class).withAnyArguments().thenReturn(mockProducer)
I think the returned value should be a mock for ReadAndWriteFiles class not a KafkaProducer
ReadAndWriteFiles readMock = Mockito.mock(ReadAndWriteFiles.class)
PowerMockito.whenNew(ReadAndWriteFiles.class).withAnyArguments().thenReturn(readMock)
Mockito.when(readMock.getAllFiles()).thenReturn(anArrayOfFiles);
The signature of the thenReturn method is as follow
OngoingStubbing<T> [More ...] thenReturn(T value);
So you are using to return a ReadAndWriteFiles you shouls return an object of the same class
Related
I created assets folder in a project, put my text file there. But when i run my app, it crashes with error:
"Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)"
I tried different ways to definite var filename for example: "assets/file.txt", "assets\file.txt", "./file.txt", but i still get the same error
package com.soft23.testfile
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material.Text
import java.io.File
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
var str = "str"
var filename = "file.txt"
File(filename).forEachLine { str = it }
setContent {
Text(text = str)
}
}
}
Similar code in IntelliJ IDEA works fine
What i did wrong?
you can get asset file in Kotlin through this way:
var reader:BufferedReader? = null
try {
//here i'm calling in Fragment, change activity?.getAssets()? = getAssets() if you calling in Activity
reader = BufferedReader(InputStreamReader(activity?.getAssets()?.open("test.txt")));
val returnString = StringBuilder()
while (true) {
val mLine = reader.readLine()
if (mLine == null) break
returnString.append(mLine + "\n")
}
//here is result
Log.d("test.txt", "string = $returnString")
} catch (e: Exception) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (e: Exception) {
//log the exception
}
}
}
make sure your .txt file into this path:
project/app/src/main/assets
I have an error ("unexpected token"). I don't know Groovy very well , but how to fix it? Part of my code:
def PriorityQueue<Agent> agentPQ = new PriorityQueue<>(agents.size(), new Comparator<Agent>() {
#Override
int compare(Agent o1, Agent o2) {
if(o1.issueCount == o2.issueCount){
if(o2.lastAssignedTime == o1.lastAssignedTime){
return o1.user.name.compareTo(o2.user.name)
}
else{
return o1.lastAssignedTime.compareTo(o2.lastAssignedTime)
}
}
else{
return o1.issueCount - o2.issueCount
}
}
})
I have an error in < case
Your problem is caused by HTML entities that encoded < and > characters:
def PriorityQueue<Agent> agentPQ = new PriorityQueue<>(agents.size(), new Comparator<Agent>() {
It should be:
def PriorityQueue<Agent> agentPQ = new PriorityQueue<>(agents.size(), new Comparator<Agent>() {
The code you have pasted wont compile neither in Groovy nor in Java.
I have the following piece of code for which I'm writing the unit test using Mockito
if (user != null) {
LDAPCustomer cust = getLDAPCustomer();
LDAPAuthorization auth = getLDAPAuthorization();
cust = getCustomerData( new LDAPInstruction(SearchType.EQUAL_TO, LdapAttribute.CUSTOMER_MAIL, user));
if (cust != null)
auth = getAuthorizationData(new LDAPInstruction(SearchType.EQUAL_TO, LdapAttribute.AUTHORIZATION_GUID, cust.getCstAuthGuid()));
if (cust != null && auth!= null && cust.getCstManageeGuids().size() == 1) {
String custGuid = cust.getCstCustGuid();
if (cust.getCstManageeGuids().get(0).equals(custGuid)) {
//No secondary user
try
{
deleteUserAssociations(cust.getCstCustGuid());
resetAuthorization(auth.getCstAuthGuid());
logger.info(cust.getCstCustGuid()+" user successfully perged.");
} catch (Exception e) {
logger.error("Error occured whie try to purging user: "+MiscUtility.getStackTrace(e));
throw new Exception("Error occured whie try to purging user: "+e.getMessage());
}
}
}
}
and here's the mockito code
int size = 1;
//Define the Stub
Mockito.doReturn(mockCustomer).when(ldap).getLDAPCustomer();
Mockito.doReturn(mockAuthorization).when(ldap).getLDAPAuthorization();
Mockito.doReturn(mockCustomer).when(ldap).getCustomerData(Mockito.any(LDAPInterface.LDAPInstruction.class));
Mockito.doReturn(mockAuthorization).when(ldap).getAuthorizationData(Mockito.any(LDAPInterface.LDAPInstruction.class));
Mockito.when(mockCustomer.getCstManageeGuids().size()).thenReturn(size);
Mockito.when(mockCustomer.getCstCustGuid()).thenReturn("mockCust");
Mockito.when(mockCustomer.getCstManageeGuids().get(Mockito.anyInt()).equals(Mockito.eq("mockCust"))).thenReturn(true);
Mockito.doNothing().when(ldap).deleteUserAssociations(Mockito.anyString());
Mockito.doNothing().when(ldap).resetAuthorization(Mockito.anyString());
I'm getting a ClassCastException as below
java.lang.ClassCastException: org.mockito.internal.creation.jmock.ClassImposterizer$ClassWithSuperclassToWorkAroundCglibBug$$EnhancerByMockitoWithCGLIB$$1ebf8eb1 cannot be cast to java.lang.String
at the line
Mockito.when(mockCustomer.getCstManageeGuids().get(Mockito.anyInt()).equals(Mockito.eq("mockCust"))).thenReturn(true);
Appreciate any help.
Solved it by breaking down the chain.
List<String> lst = new ArrayList<String>();
lst.add("mockVal");
Mockito.when(mockCustomer.getCstManageeGuids()).thenReturn(lst);
I have a library that connects to a remote API:
class Client(access_token) {
void put(key, value, callback);
void get(key, callback);
}
I want to set up a Node.js REPL to make it easy to try things out:
var repl = require('repl');
var r = repl.start('> ');
r.context.client = new Client(...);
The problem is that an asynchronous API is not convenient for a REPL. I'd prefer a synchronous one that yields the result via the return value and signals an error with an exception. Something like:
class ReplClient(access_token) {
void put(key, value); // throws NetworkError
string get(key); // throws NetworkError
}
Is there a way to implement ReplClient using Client? I'd prefer to avoid any dependencies other than the standard Node.js packages.
You can synchronously wait for stuff with the magic of wait-for-stuff.
Based on your example specification:
const wait = require('wait-for-stuff')
class ReplClient {
constructor(access_token) {
this.client = new Client(access_token)
}
put(key, value) {
return checkErr(wait.for.promise(this.client.put(key, value)))
}
get(key) {
return checkErr(wait.for.promise(this.client.get(key)))
}
}
const checkErr = (maybeErr) => {
if (maybeErr instanceof Error) {
throw maybeErr
} else {
return maybeErr
}
}
I have a case where I need to call several different web endpoints and need to do the same setup and tear down for every call. I am trying to write a more generic method where I can pass in the method I want to execute along with the package to send to the endpoint and expect a string return.
From my code I can make this call:
var ret = WebServiceHandler.Execute(WebServiceHandler.LoadNewAsset(package));
The definition of Execute looks like:
internal static string Execute<T>(Func<T, string> executeThisAction)
{
Func<T, string> resp;
Setup();
resp = executeThisAction;
CleanUp();
return resp.ToString();
}
This is one of the methods I want to execute:
internal static Func<CarsWS_AssetLoad, string> LoadNewAsset(AssetLoad package)
{
string resp;
try
{
// Make the web service call...
var assetLoadReturn = _service.LoadNewAsset(new LoadNewAssetRequest {UserCredentialsHeader = _credentials, asset = package});
// Evaluate results...
if (assetLoadReturn.LoadNewAssetResult.responseType == "Success")
resp = (result != null && !String.IsNullOrEmpty(result.asset.assetID))
? "Got assetID: " + result.asset.assetID
: "No assetID returned.";
else
resp = result.responseDescription.Trim();
}
catch (Exception ex)
{
resp = "Error calling LoadNewAsset()." + Environment.NewLine + ex.GetFullMessage();
}
return resp; // <== THIS IS NOT A VALID RETURN <== //
}
My brain is shutting off at this point. How do I return the string back up the call stack correctly???
I assume that in your LoadNewAsset method the CarsWS_AssetLoad class is actually the same as AssetLoad and it was just a editing issue with your question.
That being the case, I think this is what you want:
internal static string Execute<T>(Func<T, string> executeThisAction, AssetLoad package)
{
string resp;
Setup();
resp = executeThisAction(package);
CleanUp();
return resp;
}
internal static Func<AssetLoad, string> LoadNewAsset()
{
return package =>
{
string resp;
var assetLoadReturn = _service.LoadNewAsset(new LoadNewAssetRequest {UserCredentialsHeader = _credentials, asset = package});
if (assetLoadReturn.LoadNewAssetResult.responseType == "Success")
resp = (result != null && !String.IsNullOrEmpty(result.asset.assetID))
? "Got assetID: " + result.asset.assetID
: "No assetID returned.";
else
resp = result.responseDescription.Trim();
return resp;
};
}
The use of the variable result in the LoadNewAsset is a little confusing too. Did you mean to use LoadNewAsset instead?
The above code should be able to workable for you, but it's really not the right way to go about coding this.
I assume that the Setup & CleanUp code is all about instantiating the _service that you're calling?
So the key is to code it this way:
internal static string Execute<T>(Func<IAssetService, T, string> serviceCall, AssetLoad package)
{
string resp;
var service = Setup();
resp = serviceCall(service, package);
CleanUp(service);
return resp;
}
internal static Func<IAssetService, AssetLoad, string> GetLoadNewAssetFunc()
{
return (service, package) =>
{
string resp;
var assetLoadReturn = service.LoadNewAsset(new LoadNewAssetRequest {UserCredentialsHeader = _credentials, asset = package});
if (assetLoadReturn.LoadNewAssetResult.responseType == "Success")
resp = (result != null && !String.IsNullOrEmpty(result.asset.assetID))
? "Got assetID: " + result.asset.assetID
: "No assetID returned.";
else
resp = result.responseDescription.Trim();
return resp;
};
}
Ideally if you would bring the Setup & CleanUp code into the Execute method so that the only way to call the set-up and clean-up code is thru the Execute method.
Even better, if the service class implements IDisposable then your execute code would look like this:
internal static string Execute<T>(Func<IAssetService, T, string> serviceCall, AssetLoad package)
{
using (var service = Setup())
{
return serviceCall(service, package);
}
}
Let me know if I've missed anything.
Replace:
internal static string Execute<T>(Func<T, string> executeThisAction)
with
internal static string Execute<T>(Func<T, string> executeThisAction, T argument)
then replace:
internal static Func<CarsWS_AssetLoad, string> LoadNewAsset(AssetLoad package)
with
internal static string LoadNewAsset(AssetLoad package)
then to call it:
var ret = WebServiceHandler.Execute(WebServiceHandler.LoadNewAsset, package);