I try to learn EasyMock 3.2 by refactoring tests using jMock. Excuse me if the answer is obvious, but currently I cannot find it. I know there is a 'strict' mock which detects if the order of expected calls is wrong. But I was surprised that I don't get an error if some expectations are left. Example:
// This test passes as expected
#Test
public void connectShouldPass() {
expect(sessionMock.setTimeout(10000)).andReturn(true);
replay(sessionMock);
sessionMock.setTimeout(10000);
}
// Here I would expect an fail but it passes too
#Test
public void connectShouldPass() {
expect(sessionMock.setTimeout(10000)).andReturn(true);
expect(sessionMock.setTimeout(10000)).andReturn(true);
replay(sessionMock);
sessionMock.setTimeout(10000);
}
Is it possible to check (maybe in the #After method) if more expectations were defined than called?
Thanx, Andi
[OP found their own answer. Providing answer as an answer, rather than a comment]
EasyMock.verify(mock) does the job.
Related
I'm trying to follow the interception example shown here to get it working with EF 6 but running into a problem with the function RewriteFullTextQuery as shown in Figure 1. The interception seems to work but it does not actually execute the logic in the for loop of the RewriteFullTextQuery method because the cmd.Parameters.Count is always zero. Furthermore the cmd.CommandText property seems to be displaying the correct SQL query which I take as another piece of evidence that the interception is working correctly.
Figure 1: RewriteFullTextQuery Code Excerpt
public static void RewriteFullTextQuery(DbCommand cmd)
{
string text = cmd.CommandText;
for (int i = 0; i < cmd.Parameters.Count; i++)
{
DbParameter parameter = cmd.Parameters[i];
if (parameter.DbType.In(DbType.String, DbType.AnsiString, DbType.StringFixedLength, DbType.AnsiStringFixedLength))
{
The RewriteFullTextQuery function is being called by the ReaderExecuting function shown in Figure 2 which gives it the command argument that is causing all the trouble.
Figure 2: ReaderExecuting Function
public void ReaderExecuting(DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext)
{
RewriteFullTextQuery(command);
}
Even though my code isn't exactly the same as the example, the interception seems to be working so it is making me wonder what conditions is it that will populate the command to have a Parameters.Count of more than zero?
It works only if you pass the parameter to the query as a variable. If you use a literal EF won't use parameters.
I mean, this won't generate any parameter
context.Notes.Where(_ => _.NoteText == "CompareValue").Count();
This will
string compareValue = "CompareValue";
context.Notes.Where(_ => _.NoteText == compareValue).Count();
It turns out that it is because of the way Entity Framework generates the SQL. If you pass in a string literal as your search value to your LINQ statement it does not generate a SQL that makes use of a parameter. But if you pass in your search value as a variable, it will generate the SQL that utilizes a parameter. A solution (for dynamic queries) and more details can be found on this blog.
The code which i have written uses find Element method more than 32 times:
i wanted to create a common method for find Element
should i declare any generic method ?
A bit more of info on your code will help answer this. If you are trying to access different elements on your page then you would directly or indirectly end up making these 32 calls.
So first check if you need 32 different elements or not. If not, consider storing the results in variables and reusing them (again depends on your code/flows).
Although it won't make any difference in doing it, but if still you want you can make a method somewhat like this:
public WebElement find(String type,String locator){
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
WebElement we;
if(type.equalsIgnoreCase("xpath")){
we = driver.findElement(By.xpath(locator));
}
if(type.equalsIgnoreCase("id")){
we = driver.findElement(By.id(locator));
}
// and so on...
}
And you can use it like this:
WebElement newButton1 = find("id","button1");
WebElement newLink1 = find("xpath","//a[text()='xyz']");
This seems ok
EasyMock.expect(URLDecoder.decode("test", "UTF-8")).andThrow(new UnsupportedEncodingException("This is a test"));
This doesn't
EasyMock.expect(URLDecoder.decode((String) EasyMock.anyObject(), "UTF-8")).andThrow(new UnsupportedEncodingException("This is a test"));
This throws the following
java.lang.IllegalStateException: 2 matchers expected, 1 recorded.
This exception usually occurs when matchers are mixed with raw values when recording a method:
foo(5, eq(6)); // wrong
You need to use no matcher at all or a matcher for every single param:
foo(eq(5), eq(6)); // right
foo(5, 6); // also right
at org.easymock.internal.ExpectedInvocation.createMissingMatchers(ExpectedInvocation.java:47)
at org.easymock.internal.ExpectedInvocation.<init>(ExpectedInvocation.java:40)
at org.easymock.internal.RecordState.invoke(RecordState.java:78)
at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:40)
at
If you're going to use 1 matcher in your expectation, then you need to use all matchers.
Sadly, this isn't explained very well in the error message you get out of EasyMock, but adding an EasyMock.eq() arround the other string should do the trick.
EasyMock.expect(URLDecoder.decode((String) EasyMock.anyObject(), EasyMock.eq("UTF-8"))).andThrow(new UnsupportedEncodingException("This is a test"));
I'm currently testing different algorithms, which determine whether an Integer is a real square or not. During my research I found this question at SOF:
Fastest way to determine if an integer's square root is an integer
I'm compareably new to the Programming scene. When testing the different Algorithms that are presented in the question, I found out that this one
bool istQuadratSimple(int64 x)
{
int32 tst = (int32)sqrt(x);
return tst*tst == x;
}
actually works faster than the one provided by A. Rex in the Question I posted. I've used an NS-Timer object for this testing, printing my results with an NSLog.
My question now is: How is speed-testing done in a professional way? How can I achieve equivalent results to the ones provided in the question I posted above?
The problem with calling just this function in a loop is that everything will be in the cache (both the data and the instructions). You wouldn't measure anything sensible; I wouldn't do that.
Given how small this function is, I would try to look at the generated assembly code of this function and the other one and I would try to reason based on the assembly code (number of instructions and the cost of the individual instructions, for example).
Unfortunately, it only works in trivial / near trivial cases. For example, if the assembly codes are identical then you know there is no difference, you don't need to measure anything. Or if one code is like the other plus additional instructions; in that case you know that the longer one takes longer to execute. And then there are the not so clear cases... :(
(See the update below.)
You can get the assembly with the -S -emit-llvm flags from clang and with the -S flag from gcc.
Hope this help.
UPDATE: Response to Prateek's question in the comment "is there any way to determine the speed of one particular algorithm?"
Yes, it is possible but it gets horribly complicated REALLY quick. Long story short, ignoring the complexity of modern processors and simply accumulating some predefined cost associated with the instructions can lead to very very inaccurate results (the estimate off by a factor of 100, due to the cache and the pipeline, among others). If you try take into consideration the complexity of the modern processors, the hierarchical cache, the pipeline, etc. things get very difficult. See for example Worst Case Execution Time Prediction.
Unless you are in a clear situation (trivial / near trivial case), for example the generated assembly codes are identical or one is like the other plus a few instructions, it is also hard to compare algorithms based on their generated assembly.
However, here a simple function of two lines is shown, and for that, looking at the assembly could help. Hence my answer.
I am not sure if there is any professional way of checking the speed (if there is let me know as well). For the method that you directed to in your question I would probably do something this this in java.
package Programs;
import java.math.BigDecimal;
import java.math.RoundingMode;
public class SquareRootInteger {
public static boolean isPerfectSquare(long n) {
if (n < 0)
return false;
long tst = (long) (Math.sqrt(n) + 0.5);
return tst * tst == n;
}
public static void main(String[] args) {
long iterator = 1;
int precision = 10;
long startTime = System.nanoTime(); //Getting systems time before calling the isPerfectSquare method repeatedly
while (iterator < 1000000000) {
isPerfectSquare(iterator);
iterator++;
}
long endTime = System.nanoTime(); // Getting system time after the 1000000000 executions of isPerfectSquare method
long duration = endTime - startTime;
BigDecimal dur = new BigDecimal(duration);
BigDecimal iter = new BigDecimal(iterator);
System.out.println("Speed "
+ dur.divide(iter, precision, RoundingMode.HALF_UP).toString()
+ " nano secs"); // Getting average time taken for 1 execution of method.
}
}
You can check your method in similar fashion and check which one outperforms other.
Record the time value before your massive calculation and the value after that. The difference is the time executed.
Write a shell script where you will run the program. And run 'time ./xxx.sh' to get it's running time.
I could use some general assistance with a simple bit of Apex code. Just so you know I am a newbie to Salesforce.com, but not to web application programming (12 years but with Coldfusion and some Perl and am used to the MVC architecture), although I have not been exposed deeply to Java or C#.
So I am working on a simple controller that I'll use in a simple VF page. I'd just like to return the value and display it on the page but Im running into some syntax issues during compile. Here's my code so far:
Controller - mytest.cls
public with sharing class myTest {
public class addNewFolder {
String tmpFolderName = 'MyTestFolder';
String tmpObjectID = '22K22';
String tmpResult = 'Whoo-hoo!';
System.debug('XIX|' + tmpResult);
return tmpResult;
}
}
Error
Description Resource Path Location Type
Save error: expecting a right parentheses, found 'XIX|' mytest.cls /PREPROD/src/classes line 15 Force.com save problem
As I understand
addNewFolder
is a METHOD. So instead of writing
public class addNewFolder
you must write
public string addNewFolder() {... return tmpResult;}
I hope it will help you.
It looks like the | character is causing the error. You could try escaping the | character like this:
System.debug('XIX\\|' + tmpResult);
Or, you could use a different character:
System.debug('XIX-' + tmpResult);
Update: Upon looking more carefully at your code, I realized superfell is right (see his comment on your question above).