java.lang.AssertionError: expected - unit-testing

My TestNG test implementation throws an error despite the expected value matches with the actual value.
Here is the TestNG code:
#Test(dataProvider = "valid")
public void setUserValidTest(int userId, String firstName, String lastName){
User newUser = new User();
newUser.setLastName(lastName);
newUser.setUserId(userId);
newUser.setFirstName(firstName);
userDAO.setUser(newUser);
Assert.assertEquals(userDAO.getUser().get(0), newUser);
}
The error is:
java.lang.AssertionError: expected [UserId=10, FirstName=Sam, LastName=Baxt] but found [UserId=10, FirstName=Sam, LastName=Baxt]
What have I done wrong here?

The reason is simple. Testng uses the equals method of the object to check if they're equal. So the best way to achieve the result you're looking for is to override the equals method of the user method like this.
public class User {
private String lastName;
private String firstName;
private String userId;
// -- other methods here
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!User.class.isAssignableFrom(obj.getClass())) {
return false;
}
final User other = (User) obj;
//If both lastnames are not equal return false
if ((this.lastName == null) ? (other.lastName != null) : !this.lastName.equals(other.lastName)) {
return false;
}
//If both lastnames are not equal return false
if ((this.firstName == null) ? (other.firstName != null) : !this.firstName.equals(other.firstName)) {
return false;
}
//If both lastnames are not equal return false
if ((this.userId == null) ? (other.userId != null) : !this.userId.equals(other.userId)) {
return false;
}
return true;
}
}
and it'll work like magic

It seems you are either comparing the wrong (first) object or equals is not correctly implemented as it returns false.
The shown values are just string representations. It doesn't actually mean that both objects have to be equal.
You should check if userDAO.getUser().get(0) actually returns the user you are setting before.
Posting the implementation of User and the userDAO type might help for further clarification.

NOTE: Note directly related to this question but it's answer to my issue that got me to this question. I am sure more ppl might end-up on this post looking for this solution.
This is not precisely the a solution if Equals method needs overriding but something that I very commonly find myself blocked due to:
If you have used Capture and are asserting equality over captured value, please be sure to get the captured value form captured instance.
eg:
Capture<Request> capturedRequest = new Capture<>();
this.testableObj.makeRequest(EasyMock.capture(capturedRequest))
Assert.assertEquals(capturedRequest.getValue(), expectedRequest);
V/S
Assert.assertEquals(capturedRequest, expectedRequest);
while the compiler wont complain in either case, the Assertion Obviously fails in 2nd case

Related

How to pass LedgerJournalTrans table in resolve method of InvoiceJournalExpPartcicipantProvider class?

I have literally tried everything but still in vain. This here is InvoiceJournalExpParticipantProvider class that is supposed to provide me partici[ant names inside the workflow (all of this is custom code). Now what i want is to pass the LedgerJounalTrans table instead of the VendInvoiceInfoTable or VendInvoiceInfoLine table. I cannot seem to find a way to do this. I tried using the following code
else if (_context.parmTableId() == tableNum(LedgerJournalTrans))
{
ledgerJournalTrans = LedgerJournalTrans::findRecId(_context.parmRecId(),false);
}
But it constantly gives me an error either telling me that the operand types are of not the same types or the number of arguments passed are invalid although when i go and check the findRecId() method of ledgerJournalTrans table there are only two params being passed.
public WorkflowUserList resolve(WorkflowContext _Context, WorkflowParticipantToken _participantTokenName)
{
WorkflowUserList userList = WorkflowUserList::construct();
VendInvoiceInfoTable vendInvoiceInfoTable;
VendInvoiceInfoLine vendInvoiceInfoLine;
VendInvoiceInfoLine_Project vendInvoiceInfoLine_Project;
WorkflowParticipantExpenToken workflowParticipantExpenToken;
WorkflowParticipantExpenTokenLine workflowParticipantExpenTokenLine;
RefRecId dimensionAttributeSetRecId;
MarkupTrans markupTrans;
CompanyInfo legalEntity;
ProjTable projTable;
HcmWorker worker;
DirPersonUser personUser;
HcmPositionDetail hcmPositionDetail;
HcmPosition hcmPosition;
HcmPositionWorkerAssignment hcmPositionWorkerAssignment;
LedgerJournalTrans ledgerJournalTrans;
// check participant token name is given otherwise throw error
if(!_participantTokenName)
{
throw error('Participant name');
}
userList.add('Admin');
if (!_participantTokenName)
{
throw error("#SYS105453");
}
workflowParticipantExpenToken = WorkflowParticipantExpenToken::findName(
this.documentType(),
_participantTokenName);
if (!workflowParticipantExpenToken)
{
throw error(strFmt("#SYS313865", _participantTokenName));
}
if (_context.parmTableId() == tableNum(VendInvoiceInfoTable))
{
vendInvoiceInfoTable = VendInvoiceInfoTable::findRecId(_context.parmRecId());
}
else if (_context.parmTableId() == tableNum(VendInvoiceInfoLine))
{
vendInvoiceInfoTable = VendInvoiceInfoLine::findRecId(_context.parmRecId()).vendInvoiceInfoTable();
}

Indentifier not found in non-program loop script

I have tried to look up the "identifier not found" error only to find posts where the function must be moved outside the main loop or should use a forward declaration. However, my script is used as a module for a game engine thus has no real main loop and the function in question is called by a different function above the failing line with no issues:
// Create a Steam ID
CSteamID Steam::createSteamID(uint32 steamID, int accountType){
CSteamID cSteamID;
if(accountType < 0 || accountType >= k_EAccountTypeMax){
accountType = 1;
}
cSteamID.Set(steamID, EUniverse(k_EUniversePublic), EAccountType(accountType));
return cSteamID;
}
// Set a Steam user as someone recently played with
void Steam::setPlayedWith(int steamID){
if(SteamFriends() == NULL){
return;
}
CSteamID friendID = createSteamID(steamID);
SteamFriends()->SetPlayedWith(friendID);
}
// Get friend's Steam username
String getFriendPersonaName(int steamID){
if(SteamFriends() == NULL || steamID == 0){
return "";
}
CSteamID friendID = createSteamID(steamID);
bool isDataLoading = SteamFriends()->RequestUserInformation(friendID, true);
if(!isDataLoading){
return SteamFriends()->GetFriendPersonaName(friendID);
}
}
The ID creation function sits at the very top and these two functions come much later. The first one (setPlayedWith) succeeds no problem but the second one (getFriendPersonaName) fails with: 'createSteamID': identifier not found when compiling the script.
I'm kind of at a loss and hopefully someone can point me in the right direction.
if getFriendPersonaName() is a member function then you have forgotten to define it the correct way so it will look like:
string Steam::getFriendPersonaName(int steamID)...
if it is not a member then you can't access it. however you can Only access it if getFriendPersonaName() is a friend function where you should edit the signature to:
String getFriendPersonaName(int steamID, const steam& rhs);

Issue with a WS verifier method when migrating from Play 2.4 to Play 2.5

I have a method I need to refactor, as F.Promise has been deprecated in Play 2.5. It's pretty readable actually. It sends a request and authenticates via a custom security token and returns true if the response is 200.
public boolean verify(final String xSassToken){
WSRequest request = WS.url(mdVerifyXSassTokenURL)
.setHeader("X-SASS", xSassToken)
.setMethod("GET");
final F.Promise<WSResponse> responsePromise = request.execute();
try {
final WSResponse response = responsePromise.get(10000);
int status = response.getStatus();
if(status == 200 ) { //ok
return true;
}
} catch (Exception e) {
return false;
}
return false;
}
First thing I had to do was change this line:
final F.Promise<WSResponse> responsePromise = request.execute();
To this:
final CompletionStage<WSResponse> responsePromise = request.execute();
However, CompletionStage(T) doesn't have an equivalent get() method so I'm not sure the quickest and easiest way to get a WSResponse that I can verify the status of.
Yes, it does not. At least not directly.
What you are doing is "wrong" in the context of PlayFramework. get is a blocking call and you should avoid blocking as much as possible. That is why WS offers a non blocking API and a way to handle asynchronous results. So, first, you should probably rewrite your verify code to be async:
public CompletionStage<Boolean> verify(final String xSassToken) {
return WS.url(mdVerifyXSassTokenURL)
.setHeader("X-SASS", xSassToken)
.setMethod("GET")
.execute()
.thenApply(response -> response.getStatus() == Http.Status.OK);
}
Notice how I'm using thenApply to return a new a java.util.concurrent.CompletionStage instead of a plain boolean. That means that the code calling verify can also do the same. Per instance, an action at your controller can do something like this:
public class MyController extends Controller {
public CompletionStage<Result> action() {
return verify("whatever").thenApply(success -> {
if (success) return ok("successful request");
else return badRequest("xSassToken was not valid");
});
}
public CompletionStage<Boolean> verify(final String xSassToken) { ... }
}
This way your application will be able to handle a bigger workload without hanging.
Edit:
Since you have to maintain compatibility, this is what I would do to both evolve the design and also to keep code compatible while migrating:
/**
* #param xSassToken the token to be validated
* #return if the token is valid or not
*
* #deprecated Will be removed. Use {#link #verifyToken(String)} instead since it is non blocking.
*/
#Deprecated
public boolean verify(final String xSassToken) {
try {
return verifyToken(xSassToken).toCompletableFuture().get(10, TimeUnit.SECONDS);
} catch (Exception e) {
return false;
}
}
public CompletionStage<Boolean> verifyToken(final String xSassToken) {
return WS.url(mdVerifyXSassTokenURL)
.setHeader("X-SASS", xSassToken)
.setMethod("GET")
.execute()
.thenApply(response -> response.getStatus() == Http.Status.OK);
}
Basically, deprecate the old verify method and suggest users to migrate to new one.

How to Set Multple Regex Costraints on textbox in ZKOSS

I have a textbox which should only accept Characters:-for that first regex has been set in constraint and it should not accept some reserved keywords that are A,R,F,U .Since two different constraints are set ,i want user to see the specific message ,for first it should be Illegal Value i.e default zkoss error and when he/she enters a reserved character ,it should show that reserved code has been put.
But somehow the following code doesnt work :
field_code.setConstraint("/[a-zA-Z]/ : {Illegal Value} ,/[^AaRrUuFf]/ : Reserved Code");
The output is the first regex works fine but on offending the same " {Illegal Value} ,/[^AaRrUuFf]/ : Reserved Code" is displayed as error.
You can't do it in the zul, but with help of a SimpleConstraint you could create this.
Create your own class, and extend SimpleConstraint.
Then hold 2 Matcher vars for each constraint.
At last, override the Validate method to something like this :
#Override
public void validate(Component comp, Object value) {
if (value != null && value instanceof String) {
String stringValue = (String) value;
if (!expression1.reset(stringValue).matches()) {
throw new WrongValueException(comp, errorMsg1);
}
if (!expression2.reset(stringValue).matches()) {
throw new WrongValueException(comp,errorMsg2);
}
} else {
// do what needs to be done when value is null or not a String.
}
}

JavaBeans property with if statement

I have a label form JavaFx to disply if an operation was succeed or not. This should updated automaticaly when the value changed
public class operation {
private BooleanProperty success = new SimpleBooleanProperty();
public final boolean getSuccess() {
return success.get();
}
public final void setSuccess(boolean value) {
success.set(value);
}
public BooleanProperty successProperty() {
return success;
}
}
there is somewhere this code:
operation.setSuccess(true);
and this:
label1.textProperty().bind(Bindings.format("%s", operation.successProperty() != null || false? "succeed": "not succeed" ));
The Problem successProperty() is not value and if I invoke getValue() it will not updated on UI
Your condition never changes. operation.successProperty() != null just checks whether the reference returned by the method successProperty() is null: it never is.
I think you want
label1.textProperty().bind(Bindings
.when(operation.successProperty())
.then("succeed")
.otherwise("not succeed"));