A query on Junit test methods - junit

public void testNullsInName() {
fail("sample failure");
Person p = new Person(null, "lastName");
assertEquals("lastName", p.getFullName());
p = new Person("Tanner", null);
assertEquals("Tanner ?", p.getFullName());
}
I have difficulty in understanding fail in Junit .
Could anybody please tell me what is the use of fail in the above method ??
( I want to know what it is responsible to do there )
And typically if i want to add this below line also in the above code . how could i add
Person p = new Person(null, "lastName"); // After this statement
if(p==null)
{
// then dont proceed further to the further execution
// Show the Junit Test case as PASS .
}
Please help me .

The fail("sample failure"); -statement in the first case will cause the test to be reported as failed with reason "sample failure" when the statement is run. No idea why it's placed as first statement in the test case, as it will cause the test to fail immediately and the rest of the statements are never executed. As for the second case, simply returning from the method will cause the test to pass.

Related

Java 8 Streams - Throwing an exception in the middle of an iteration

I have the following array
ArrayList<Car> list = new ArrayList<>();
I want to iterate it and throw an exception if it contains a certain value
i.e.
if at least one
list.stream.filter(x -> x.color.equals("Black"));
then I want to stop iteration and throw an exception.
Is there a way?
You could use anyMatch for this:
boolean matched = list.stream().anyMatch(x -> x.color.equals("Black"));
if(matched) throw new SomeException();
Since it does not evaluate the rest of the pipeline if the condition is satisfied for one element when iterating through it, and that it returns false if the stream is empty, I think this is what you are looking for.
Of course, you could do it in a single statement but it may not improve readability depending on the situation:
if(list.stream().anyMatch(x -> x.color.equals("Black"))) {
throw new SomeException();
}
Easiest is:
list.forEach( x -> {
if(x.color.equals("Black")) throw new RuntimeException();
});

error handling when performing 2 mysql queries

I have constructed a function where two queries are performed. Both of these queries insert data into two separate tables, data that is related to the registration of a user.
In one table things like username,password are held and in the other table stuff like address, phone etc...
Here is the function:
function register_biz_user($post,$connection)
{
$name=$connection-> real_escape_string($_POST['name']);
$lastname= $connection->real_escape_string($_POST['lastname']);
$pass_hashed = password::hash($_POST['password']);
$passwd= $connection->real_escape_string($pass_hashed);
$buztype= $connection->real_escape_string($_POST['buztype']);
$usertype= $connection->real_escape_string($_POST['usertype']);
$address= $connection->real_escape_string($_POST['address']);
$city= $connection->real_escape_string($_POST['city']);
$municipality= $connection->real_escape_string($_POST['municipality']);
$url= $connection->real_escape_string($_POST['wwwaddress']);
$email= $connection->real_escape_string($_POST['e-mail']);
$phone= $connection->real_escape_string($_POST['phone']);
$hash =$connection->real_escape_string(md5( rand(0,1000) )) ;
$connection->set_charset("utf8");
$result1 = $connection->query("insert into users values
(NULL,'" .$name. "','" .$lastname . "','".$email."','". $passwd."','".
$hash."','". $usertype."')");
if (!$result1) {
throw new Exception('error');
return false;
}
else{$result2=$connection->query("insert into business_users values
('".$connection->insert_id."','" .$address."','".$url ."','".$phone.
"','".$city. "','".$municipality. "','".$buztype. "')");
}
if(!$result2)
{ throw new Exception('error');
return false;}
return true;
}
And here is my problem:
If you look at the code you might notice that there is the problem that the 1st query runs without problem and the second throws an exception or vice verca.
My point is that there is the danger that the db WILL have ONLY partial data of the registered user. The goal is that either both queries run successfully or none runs.
How I must write the above code such that I can achieve the above statement?
I hope I was clear enough.
Use transactions: http://dev.mysql.com/doc/refman/5.0/en/commit.html
BEGIN
... queries ...
COMMIT or ROLLBACK
Note: "or vice verca" - that's not possible. In that case the 2nd query never gets executed.
Note2:
what's $post? seems to be unused.
why don't you use prepared statements? escaping everyhing is very error prone.
why do you have a procedural interface, passing $connection? you should have objects which know about the database connections... you have mixed code for at least 3 different layers... not necessary bad if you plan to create write-once-get-rid-of-code but probably not a good idea for a project which you have to maintain for months/years.

how NamedParameterJdbcTemplate.update really works with Spring and MySQL

Ok, I've probably dug up the entire Google land and still couldn't find anything that could possibly answer my question.
I have my little foo method that does some deleting like this:
private void foo()
{
jdbcNamedParameterTemplate.update(sqlString, params); //1
jdbcNamedParameterTemplate.update(sqlString2, params2); //2
}
sqlString and sqlString2 are just delete statements like "Delete * from FooBar".
So when I get to the second call to update, do I have any guarantee that whatever operation the first one invokes in the database has already finished?
If you do that two in one session, and non multithreading, then yes the first one invokes in the database has already finished before the second update.
But if not in the same session you can check the version to check if the object already changed or not
int oldVersion = foo.getVersion();
session.load( foo, foo.getKey() ); // load the current state
if ( oldVersion != foo.getVersion()) { .... }// if true then the object has been changed

Understanding cyclomatic complexity

I have some piece of code that basically looks like this:
public MyObject getData(boolean someFlag) {
String select1 = "SELECT * FROM myTable WHERE someInteger = ?";
SqlHostvariablen hostvars = new SqlHostvara();
hostvars.addInteger(myField.getSomeInteger);
String[][] selarray = SqlHelper.doSelectAsMatrix(select1, hostvars);
if (selarray.length == 0) {
throw new IllegalArgumentException("Nothing found");
}
MyObject foo = new MyObject();
int i = 0;
foo.setSomething1(selarray[0][i++]);
foo.setSomething2(selarray[0][i++]);
foo.setSomething3(selarray[0][i++]);
foo.setSomething4(selarray[0][i++]);
foo.setSomething5(selarray[0][i++]);
foo.setSomething6(selarray[0][i++]);
foo.setSomething7(selarray[0][i++]);
foo.setSomething8(transformSomething8(selarray[0][i++]));
foo.setSomething9(selarray[0][i++]);
foo.setSomething10(selarray[0][i++]);
String someValue1 = selarray[0][i++];
String someValue2 = selarray[0][i++];
foo.setSomething11(selarray[0][i++]);
doSomethingWithFoo(foo, someFlag, someValue1, someValue2);
doSomethingElseWithFoo(foo);
return foo;
}
The identifiers and SQL statement are anonymized but otherwise my method looks the same.
Now Checkstyle claims that the cyclomatic comlexity if this method is 12. I always thought I knew what CC was and from my knowledge I'd say this methods CC is 2. There is one if that creates a new path through the code and the control flow graph therefore has 2 paths/exit points. I don't see where else there should be a path through the code.
Am I missing something entirely or is Checkstyle just wrong?
Turned out this was a Checkstyle error. While not even cleaning the problem did the trick, after a system restart the warning was gone. An Eclipse restart might have been enough, no way to know for sure.

How do I handle the SqlException "No Records Found" when using LINQ to SQL?

I'm using LINQ to SQL to call sprocs at my company. Normally it works great but on some queries, if nothing is found it will throw a SqlException "No Records Found".
How should I handle this case?
Here is an example call I would make:
/// <summary>
/// Gets the pending messages.
/// </summary>
/// <param name="historySearchCriteria">The history search criteria.</param>
/// <returns><c>List</c> of pending messages.</returns>
public List<PendingMessage> GetPendingMessages(HistorySearchCriteria historySearchCriteria)
{
using (MessageDataContext db = new MessageDataContext(DatabaseProperties.MessageConnectionString))
{
List<PendingMessage> pendingMessages = new List<PendingMessage>();
pendingMessages.AddRange(db.usp_search_message_pending(historySearchCriteria.AccountId,
historySearchCriteria.TrackingNumber,
historySearchCriteria.StartDateTime,
historySearchCriteria.EndDateTime)
.Select(p => new PendingMessage()
{
Account = p.account,
ActionType = (OrderActionType) Enum.Parse(typeof(OrderActionType), p.action_type.ToString()),
AttemptsRemaining = p.attempts_remaining,
Message = p.message
}));
return pendingMessages;
}
}
What is the best way to handle the fact that I simply want to return an empty list if no records are found.
You could simply catch that Exception, and return new List<PendingMessage>; within the handler.
You could use DefaultIfEmpty.
Somthing like:
pendingMessages.AddRange(
db.usp_search_message_pending
(
historySearchCriteria.AccountId,
historySearchCriteria.TrackingNumber,
historySearchCriteria.StartDateTime,
historySearchCriteria.EndDateTime
)
.DefaultIfEmpty()
.Select( /* select clause here */)
);
Where does the text "No Records Found" come from?
Execute the stored procedure from Management Studio using the same parameters that result in the exception.
Does SSMS report an error?
If not, separate the C# line into 3 steps:
Invoking the stored procedure
Check for != null and invoke Select()
Check for != null and call AddRange()