It is possible to do a x.toEqual('hello').or.toEqual('bye')?
I want to be able to do Expects that have multiple correct possibilities.
You can always do an if statement that returns a boolean and then check if that boolean is true.
var test = false;
if(x=='hello' || x=='bye'){
test = true;
}
expect(test).toEqual(true);
Related
I am issuing calls that return an Option that contains a Result which contains another Option that contains custom variants.
I am only ever interested in a specific chain of variant results like this:
if let Some(Ok(Some(CustomVariant(Some(value))))) = expr {
// handle value case
}
This is getting quite verbose and not really helpful, since I actually treat it as a single Result in all of my code. Can I somehow alias this code so that instead of writing the entire chain of Options and Results I can do something similar to:
alias TheCase(value) = Some(Ok(Some(CustomVariant(Some(value))));
if let TheCase(value) = expr {
//handle value
}
You don't need such an alias, just use a function to retrieve the one case you want:
fn oneCaseICareAbout(value: &Option<Result<Option<Foo>, Bar>>) -> Option<&Foo> {
if let Some(Ok(Some(CustomVariant(Some(value)))) = value {
Some(value)
} else {
None
}
}
if let Some(value) = oneCaseICareAbout(expr) {
//handle value
}
I would however consider refactoring your code not to use such a type. Option<Result<_, _>> is already a red flag, but Some(Ok(Some(CustomVariant(Some(…)))) is just on the edge of insanity!
I'm having a validate method that return a boolean.
I'm using invoking this method (Java 7) as follow:
boolean isValid = true;
for (String key: aMap.keySet()) {
isValid &= validate(key, aMap.get(key));
}
I would like to rewrite this code in Java 8.
Java 8 allows iterating across a Map using:
aMap.forEach((k,v) -> validate(k, v));
But this won't work:
aMap.forEach((k,v) -> isValid &= validate(k, v));
Question
How can I rewrite the the Java 7 code into Java 8 to achieve the same result?
Note:
I asked a similar question here . The difference in this post is that I want to iterate this time across all the items of the Map (for the validate method to build a validation report). isValid must return true if no validation error occurred, or false if at least one occurred.
You can use
boolean isValid = aMap.entrySet().stream()
.map(e -> validate(e.getKey(), e.getValue()))
.reduce(true, Boolean::logicalAnd);
as, unlike anyMatch, allMatch, etc, Reduction knows no short-circuiting. However, your requirement of executing all validate method calls suggests that there are side-effects within that method. It’s important to understand that these side effects must be non-interfering, i.e. it should not matter in which order these method calls are made and even concurrent evaluation of multiple elements should not break it.
Even when these requirements are met, it is rather discouraged to have such side-effects in a functional operation. E.g., the next developer looking at your code may say, “hey that looks like we should use allMatch here”…
So I’d stay with the loop. But when processing the associations of a Map, you should not loop over the entrySet(), to perform a lookup for every key, but rather use
boolean isValid = true;
for(Map.Entry<String, ValueType> e: aMap.entrySet())
isValid &= validate(e.getKey(), e.getValue());
Starting with Java 10, you may use
boolean isValid = true;
for(var e: aMap.entrySet()) isValid &= validate(e.getKey(), e.getValue());
eliminating the most annoying syntactical element of that loop.
The issue with aMap.forEach((k,v) -> isValid &= validate(k, v)); is that the variable captured in a lambda expression should be final or effectively final. This is the same for anonymous inner classesin Java.
So, to answer your query, you can convert isValid to a final one element array, like this:
final boolean[] isValid = {true}; and then
aMap.forEach((k,v) -> isValid[0] &= validate(k, v));
You can also probably make it atomic, but that would require more code changes. This solution is much simpler.
I have the following Test:
[Test]
public void GrantResourceOwnerCredentials_NullClientID_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() =>{ new ApplicationOAuthProvider(null,null); });
}
The test passed, but when i run code coverage, it highlights
new ApplicationOAuthProvider(null,null);
as "Coverage Partially Touched Area".
How do i fix that?
By the way, I am new to Unit Testing/Code Coverage so go easy on me.
Thanks
When you see a result of "Partially touched", what that means is that there are multiple code paths that can be traversed through a method (such as through an if block, a null check, etc.), and only one path was executed by your tests.
For example, if you had the following method:
public string IsThisEvenOrOdd(int number)
{
return (number % 2 == 0) ? "Even" : "Odd";
}
And you write the following unit test:
public string IsThisEvenOrOdd_PositiveEvenNumber_ReturnsEven()
{
var number = 2;
var expected = "Even";
var actual = IsThisEvenOrOdd(number);
Assert.AreEqual(expected, actual);
}
If you run that test, it should succeed. However, it only tests one path - the "Even" path. You'll need to write at least one other test to test the "Odd" result before that method will show up as "fully covered" by MSTest.
It's possible to call another method to check something, like a boolean, and stop it (return or wathever) from it? i mean:
Method 1:
code
call method 2: ?
code
Method 2:
if(wathever){
make method 1 return
}
else{
continue
}
EDIT: yes java sorry, thanks for answers! Also yes i know how to use booleans this way, this didn't solved my question, don't want to check a returned boolean, i want to directly make the method 1 return, i suppose is not possible but thanks anyway :)
Oh, and just to actually keep my promise about LOLcode, here's a little function that returns or does something else based on its only Boolean argument:
HOW DUZ I BREAK_OUTTA_FUNCTION YR FLAG
IZ FLAG WIN, O RLY?
YA RLY BTW if flag is `WIN` (true)
GTFO BTW return
NO WAY
BTW do something else if `flag' is LOSE (false)
OIC
IF U SAY SO
So you basically want a way for a method to force the invoking method to exit?
Return an out parameter or boolean from the method to indicate to the invoking method that it needs to exit.
public void Method1()
{
if(!method2())
return;
// do stuff
}
public bool Method2()
{
if(check) {
return false;
}
// do other stuff
return true;
}
You can use boolean return values / a boolean conditional based on the return value of method two. But you can not really forward a return statement. My example is language indiscriminate since you did not provide a language.
def methodOne():
if (!methodTwo()):
return
else:
<code>
def methodTwo():
if (whatever):
return false
else:
<code>
Im making firefox extension. One function stores value in every tab, to use it later by other function.
function setValue(value) {
var attr = gBrowser.document.createAttribute("value");
attr.value = value;
gBrowser.document.attributes.setNamedItem(attr);
};
function getValue() {
var attr = gBrowser.document.attributes.getNamedItem("value");
if (attr != undefined && attr != null)
return attr.value;
else
return null;
};
For some reason, this doesn't work. Can you spot an error in my code?
Function getValue() should get value of active tab.
There are more errors than code here:
There's no gBrowser.document - you probably meant gBrowser.ownerDocument or just document (equivalent but simpler).
Neither is gBrowser.document.attributes, you meant gBrowser.attributes.
Using attributes seems very weird, an equivalent to the fixed up version of your code would be gBrowser.setAttribute("value", value) and gBrowser.getAttribute("value")
The fixed up code still isn't what you probably need and you didn't specify what exactly do you need (gBrowser.mCurrentTab.setAttribute?)