Using Mockito "when" with parameters that could contain certain values? - unit-testing

I'm new to Mockito and am trying to figure out if this case is possible.
I am trying to mock a class, where there's a method that takes in 3 parameters, and based on whether or not the first parameter contains some substring, I return something different from the Mock.
Could someone help point me towards what I can use? I have been digging around Mockito and haven't had any luck.
Example, I'm trying to do something like this (pseudocode):
when(myMock.lookup(anyStringThatContains("abc"), anyString(), anyString())
.thenReturn(ImmutableList.of(...someItems))
when(myMock.lookup(anyStringThatContains("def"), anyString(), anyString())
.thenReturn(ImmutableList.of(...otherItems))
Additionally:
What happens if the string that I need to check is contained within the object passed in the parameter?
ie. What if the first parameter has a field, line and that's what needs to be checked instead of having the string at the top level?

You can use eq() matcher to match exact string:
when(myMock.lookup(eq("abc"), anyString(), anyString())
.thenReturn(ImmutableList.of(...someItems))
when(myMock.lookup(eq("def"), anyString(), anyString())
.thenReturn(ImmutableList.of(...otherItems))
If you need to match only some part of a string, you can use matches() (passing a regex into it) instead:
when(myMock.lookup(matches(".*abc.*"), anyString(), anyString())
.thenReturn(ImmutableList.of(...someItems))
when(myMock.lookup(matches(".*def.*"), anyString(), anyString())
.thenReturn(ImmutableList.of(...otherItems))
About addition: if your string is stored in a variable, you can simply use string concatenation:
String str = "abc";
when(myMock.lookup(matches(".*" + str + ".*"), anyString(), anyString())
.thenReturn(ImmutableList.of(...someItems))
or (if it stored inside a field of an object) - like this:
MyObject myObject = new MyObject();
myObject.setLine("abc");
when(myMock.lookup(matches(".*" + myObject.getLine() + ".*"), anyString(), anyString())
.thenReturn(ImmutableList.of(...someItems))

Related

Use IndexOf and Substring to catch a string AFTER IndexOf

I just came across something I would ask you for other possible solutions.
I have a string:
string text = "This is a very serious sample text, not a joke!"
Now I would like to find the position of the word "serious" and get the rest of the string AFTER "serious".
One way I would solve this is:
$text="This is a very serious sample text, not a joke!"
$start=($text).IndexOf("serious")
(($text).Substring($start+"serious".Length)).TrimStart()
I am sure there is a regex solution for this as well, but I was wondering if I can use IndexOf() and then Substring to get the rest of the string AFTER "serious".
I was also looking into this post here: Annoying String Substring & IndexOf but either it is not the solution/question I am looking for or I didnt understand...
Thanks for your help in advance, Adis
Since one of SubString's overloads takes only the starting index, first find where serious (note the trailing space) is and then pick substring from that point plus length of what was searched for.
By putting the search term into a variable, one can access its length as a property. Changing the search term would be easy too, as it requires just updating the variable value instead of doing search and replace for string values.
Like so,
$searchTerm = "serious "
$start = $text.IndexOf($searchTerm)
$text.Substring($start + $searchTerm.length)
sample text, not a joke!
As for a simple regex, use -replace and pattern ^.*serious . That would match begin of string ^ then anything .* followed by seroius . Replacing that with an empty string removes the matched start of string. Like so,
"This is a very serious sample text, not a joke!" -replace '^.*serious ', ''
sample text, not a joke!
There might be cases in which Extension Methods would be straight-forward solution. Those allow adding new methods to existing .Net classes. The usual solution would be inheriting, but since string is sealed, that's not allowed. So, extension methods are the way to go. One case could be creating a method, say, IndexEndOf that'll return where search term ends.
Adding .Net code (C# in this case) is easy enough. Sample code is adapted from another answer. The IndexEndOf method does the arithmetic and returns index where the pattern ended at. Like so,
$code=#'
public class ExtendedString {
public string s_ {get; set;}
public ExtendedString(string theString){
s_ = theString;
}
public int IndexEndOf(string pattern)
{
return s_.IndexOf(pattern) + pattern.Length;
}
public static implicit operator ExtendedString(string value){
return new ExtendedString(value);
}
}
'#
add-type -TypeDefinition $code
$text = "This is a very serious sample text, not a joke!"
$searchTerm = "serious "
$text.Substring(([ExtendedString]$text).IndexEndOf($searchTerm))
sample text, not a joke!

Emberjs String not working with javascript string

If I do var str1 = "a string" then I get a string literal (for want of a better term) when I look at the string in the debugger. i.e. it just displays "a string"
However if i do var str2 = new Ember.String("another string") then it appears as a String object with the chars listed as array items rather than just as "another string"
This is a problem because if i have an array like var myarray = ["str1", "str2","str3"] and do myarray.contains(myvar) it won't work if myvar is of type String.
Now I came across this because of an action handler where I had passed "this" and found it to have become type String. What on earth is going on!
How can I turn my String back into a raw js string so it can be used in lookups in my array of constants?
The object you're getting is not an 'Ember string', it's just a Javascript string object created via new String(''). I don't know why you're coming across one, but if you do, just convert it to a string primitive. You can either do that with the toString() method, or (the safer way) by just concatenating an empty string: str2 + ''.

Regex Matching and Deleting/Replacing a string

So I am trying to parse through a file which has multiple "footers" (the file is an output that was designed for printing which my company wants to keep electronically stored...each footer is a new page and the new page is no longer needed as).
I am trying to look for and remove lines that look like:
1 of 2122 PRINTED 07/01/2013 04:46 Page : 1 of 11
2 of 2122 PRINTED 07/01/2013 04:46 Page: 2 of 11
3 of 2122 PRINTED 07/01/2013 04:46 Page: 3 of 11
and so on
I then want to replace the final line (which would read something like "2122 of 2122") with a "custom" footer.
I am using RegEx, but am very new to using it so how should my RegEx look in order to accomplish this? I plan on using the RegEx "count" function to find out when I've found the last line and then do a .replace on it.
I am using VB .NET, but can translate C# if required. How can I accomplish what I'm looking to do? Specifically I only care about matching/removing of a match so long as the # of matches > 1.
Here's one I created with RegExr:
/^(\d+\s+of\s+\d+)(?=\s+printed)/gim
It matches (number)(space)('of')(space)(number) at the beginning of a line, and only if it is followed by (space)('printed'), case insensitive. The /m flag turns ^ and $ into line-aware boundaries.
This is how I ended up doing it...
Private Function FixFooters(ByVal fileInput As String, Optional ByVal numberToLeaveAlone As Integer = 1) As String
Dim matchpattern As String = "^\d+\W+of\W+\d+\W+PRINTED.*$"
Dim myRegEx As New Regex(matchpattern, RegexOptions.IgnoreCase Or RegexOptions.Multiline)
Dim replacementstring As String = String.Empty
Dim matchCounter As Integer = myRegEx.Matches(fileInput).Count
If numberToLeaveAlone > matchCounter Then numberToLeaveAlone = matchCounter
Return myRegEx.Replace(fileInput, replacementstring, matchCounter - numberToLeaveAlone, 0)
End Function
I used myregextester.com to get the inital matchpattern. Since I wanted to leave the last footer alone (to manipulate it further later on) I created the numberToLeaveAlone variable to ensure we don't remove ALL of the variables. For the purposes of this program I made the default value 1, but that could be changed to zero (I only did it for readability in the calling code as I know I will ALWAYS want to leave one...but I do like to reuse code). It's fairly fast, I'm sure there are better ways out there, but this one made the most sense to me.

DevExpress XtraEditors TextEdit mask to completely replace exact string?

I have an exact string which is retrieved from a database. For sake of argument, lets use this as an example:
string dataText = "set of characters";
I need to be able to replace that text with some other text, also retrieved from a database using the mask. For sake of argument, lets use this replacement text as an example.
string replacementText = "this string is private!";
I need to complete this line, but I can't figure out the regex I would need to use to force the mask to replace the dataText with replacementText
textEditSomething.Properties.Mask.EditMask = ???
How do I do this?

Using a Variable in an AS3, Regexp

Using Actionscript 3.0 (Within Flash CS5)
A standard regex to match any digit is:
var myRegexPattern:Regex = /\d/g;
What would the regex look like to incorporate a string variable to match?
(this example is an 'IDEAL' not a 'WORKING' snippet) ie:
var myString:String = "MatchThisText"
var myRegexPatter_WithString:Regex = /\d[myString]/g;
I've seen some workarounds which involve creating multiple regex instances, then combine them by source, with the variable in question, which seems wrong. OR using the flash string to regex creator, but it's just plain sloppy with all the double and triple escape sequences required.
There must be some pain free way that I can't find in the live docs or on google. Does AS3 hold this functionality even? If not, it really should.
Or I am missing a much easier means of simply avoiding this task that I'm simply naive too due to my newness to regex?
I've actually blogged about this, so I'll just point you there: http://tyleregeto.com/using-vars-in-regular-expressions-as3 It talks about the possible solutions, but there is no ideal one like you mention.
EDIT
Here is a copy of the important parts of that blog entry:
Here is a regex to strip the tags from a block of text.
/<("[^"]*"|'[^']*'|[^'">])*>/ig
This nifty expression works like a charm. But I wanted to update it so the developer could limit which tags it stripped to those specified in a array. Pretty straight forward stuff, to use a variable value in a regex you first need to build it as a string and then convert it. Something like the following:
var exp:String = 'start-exp' + someVar + 'more-exp';
var regex:Regexp = new RegExp(exp);
Pretty straight forward. So when approaching this small upgrade, that's what I did. Of course one big problem was pretty clear.
var exp:String = '/<' + tag + '("[^"]*"|'[^']*'|[^'">])*>/';
Guess what, invalid string! Better escape those quotes in the string. Whoops, that will break the regex! I was stumped. So I opened up the language reference to see what I could find. The "source" parameter, (which I've never used before,) caught my eye. It returns a String described as "the pattern portion of the regular expression." It did the trick perfectly. Here is the solution:
var start:Regexp = /])*>/ig;
var complete:RegExp = new RegExp(start.source + tag + end.source);
You can reduce it down to this for convenience:
var complete:RegExp = new RegExp(/])*>/.source + tag, 'ig');
As Tyler correctly points out (and his answer works just fine), you can assemble your regex as a string end then pass this string to the RegExp constructor with the new RegExp("pattern", "flags") syntax.
function assembleRegex(myString) {
var re = new RegExp('\\d' + myString, "i");
return re;
}
Note that when using a string to store a regex pattern, you do need to add some extra backslashes to get it to work right (e.g. to get a \d in the regex, you need to specify \\d in the string). Note also that the string pattern does not use the forward slash delimiters. In other words, the following two statements are equivalent:
var re1 = /\d/ig;
var re2 = new Regexp("\\d", "ig");
Additional note: You may need to process the myString variable to escape any backslashes it might contain (if they are to be interpreted as literal). If this is the case the function becomes:
function assembleRegex(myString) {
myString = myString.replace(/\\/, '\\\\');
var re = new RegExp('\\d' + myString);
return re;
}