I see in unit tests for Android created in Kotlin the code like this
`when`(context.getSharedPreferences(anyString(), anyInt())).thenReturn(sharedPreferences)
Could you explain me why when is inside `` ? If I remove `` around when I see an issue that thenReturn could not be resolved.
when is a keyword in Kotlin, as it's used in the when expression. In Mockito, there is a static function that's also called when. This can happen because when wasn't a keyword in Java, so it was available for identifier naming.
The backticks are special syntax that make these functions defined in Java still callable from Kotlin.
Ps. You might want to look into mockito-kotlin, it makes a couple Mockito-related tasks simpler in Kotlin, for example it renames the when function to whenever so that it's easier and nicer to call.
If you don't want to depend on another third party library as suggested in the accepted answer, you may want to take a look at BDDMockito (part of Mockito already). This basically just changes the style you write tests with Mockito and happens to provide Kotlin-friendly function names, which don't need to be escaped like when:
//Given
given(calcService.add(20.0,10.0)).willReturn(30.0);
//when
double result = calcService.add(20.0,10.0);
//then
Assert.assertEquals(result,30.0,0);
Related
Variable.h
....
#define BLAH = "blahstring"
.....
Hi,
How do we mock a variable under #define? Google mock docs talks about mostly methods and objects, but not mocking constants. Closest I can think of delegating call to fake class have it returned test value.
I have header file with list of variables, I want to mock it so that when calling BLAH in test, I get "mockblahstring" instead of "blahstring".
Any example code would help.
thanks.
A #define is not a constant.
It is a macro (see here for further reading). The compiler kicks in and replaces all occurrences of that macro long before any gmock library gets "its fingers" on it.
In other words: your compiled object does not contain any BLAH "object". It only contains the corresponding string in all those places where you wrote down BLAH.
In that sense: there is no way in mocking "entities" that simply don't exist any more.
The real answer here: that is one of the many reasons why you absolutely never ever should use preprocessor macros as "constants". Because, they aren't constants! There are still places where they make sense, but definitely not as replacement for constants.
In that sense: you should better step back and learn about such basic essentials before doing anything else.
Hoping someone can provide an explain-like-I’m-five elucidation of the difference between the following types of functions within Famo.us, and when it’s appropriate to use them:
sampleFunction() {}
_sampleFunction() {}
SampleView.prototype.sampleFunction() {}
.bind and .call are also thrown around a lot…I understand them vaguely but not as concretely as I’d like. That might be a different question, but please feel free to use them in your explanation!
Apologies for the vagueness...wish there was more regarding this in famo.us university.
None of what you're looking at is syntax specific to Famo.us. It's actually common, if intermediate level, VanillaJS.
The _ is simply a coding convention to denote that a specific function should belong to the parent scope (ie a member/private function, whatever you prefer to call it). Javascript doesn't really have support for encapsulation - the act of blocking other classes and objects from accessing another class's functions and variables. While it is possible, it's quite cumbersome and hacky.
You'll see that Famo.us uses the underscore convention to denote that a function is a member of the class using it. Some of these functions are actually just aliases to the actual Javascript native function, for example ._add actually just call's Javascript's .add method. Of course, ._add could be updated in the future on Famo.us's end to do more in the future if that's required. You really wouldn't want to try and write over the native Javascript add. That's super bad.
The other upshot is that you can document that class and say that you can and should use the _add method for a specific purpose/scenario. You'll see that in the API docs.
Understanding prototype is a core part of what it means to be a Javascript Programmer, after all, it is a prototype driven language. MDN has a much better explanation than anything I can offer here but it's basically at the core of your classes.
If you want to extend off of an existing class (say, create your own View or Surface type) you would extend it's prototype. Check out Famous Starter Kit's App examples and see how many of them create an "AppView" class, which takes the prototype of the core View, copies it for itself, and then adds it's own functions, thus extending View without ruining the original copy.
I am looking for a way to turn some long and confusing API function names into shorter types to reduce the amount of typing and over all errors due to misspelling.
For example : I would like to take gtk_functionName(); and make it a variable like so. doThis = gtk_functionName;
Sometimes the code will have lots of repeating suffix. I want to know if I can take this g_signal_connect_ and turn it into this connect so I could just type connectswapped instead of g_signal_connect_swapped.
I am looking to do this in C\C++ but would be happy to know how its done in any language. I thought I had seen a code that did this before but I can not figure out what this would be called so searching for it has been fruitless.
I am sure this is possible and I am just not able to remember how its done.
I believe what you are wanting to do is apply the Facade Pattern, which is to present a simplified interface to a larger, more complex body of code.
What this basically means is you define your own simplified interfaces for the functionality you want. The implementation of these interfaces use the longer more complex packages you want to simplify. After that, the rest of your code use the simplified interfaces instead of the complex package directly.
void doThis (That *withThat) {
gtk_functionName(withThat->arg1, withThat->arg2 /* etc. */);
}
I currently use a simple convention for my unit tests. If I have a class named "EmployeeReader", I create a test class named "EmployeeReader.Tests. I then create all the tests for the class in the test class with names such as:
Reading_Valid_Employee_Data_Correctly_Generates_Employee_Object
Reading_Missing_Employee_Data_Throws_Invalid_Employee_ID_Exception
and so on.
I have recently been reading about a different type of naming convention used in BDD. I like the readability of this naming, to end up with a list of tests something like:
When_Reading_Valid_Employee (fixture)
Employee_Object_Is_Generated (method)
Employee_Has_Correct_ID (method)
When_Reading_Missing_Employee (fixture)
An_Invalid_Employee_ID_Exception_Is_Thrown (method)
and so on.
Has anybody used both styles of naming? Can you provide any advice, benefits, drawbacks, gotchas, etc. to help me decide whether to switch or not for my next project?
The naming convention I've been using is:
functionName_shouldDoThis_whenThisIsTheSituation
For example, these would be some test names for a stack's 'pop' function
pop_shouldThrowEmptyStackException_whenTheStackIsEmpty
pop_shouldReturnTheObjectOnTheTopOfTheStack_whenThereIsAnObjectOnTheStack
Your second example (having a fixture for each logical "task", rather than one for each class) has the advantage that you can have different SetUp and TearDown logic for each task, thus simplifying your individual test methods and making them more readable.
You don't need to settle on one or the other as a standard. We use a mixture of both, depending on how many different "tasks" we have to test for each class.
I feel the second is better because it makes your unit tests more readable to others as long lines make the code look more difficult to read or make it more difficult to skim through. If you still feel there's any ambiguity as for what the test does, you can add comments to clarify this.
Part of the reasoning behind the 2nd naming convention that you reference is that you are creating tests and behavioural specifications at the same time. You establish the context in which things are happening and what should actually then happen within that context. (In my experience, the observations/test-methods often start with "should_," so you get a standard "When_the_invoicing_system_is_told_to_email_the_client," "should_initiate_connection_to_mail_server" format.)
There are tools that will reflect over your test fixtures and output a nicely formatted html spec sheet, stripping out the underscores. You end up with human-readable documentation that is in sync with the actual code (as long as you keep your test coverage high and accurate).
Depending on the story/feature/subsystem on which you're working, these specifications can be shown to and understood by non-programmer stakeholders for verification and feedback, which is at the heart of agile and BDD in particular.
I use second method, and it really helps with describing what your software should do. I also use nested classes to describe more detailed context.
In essence, test classes are contexts, which can be nested, and methods are all one line assertions. For example,
public class MyClassSpecification
{
protected MyClass instance = new MyClass();
public class When_foobar_is_42 : MyClassSpecification
{
public When_foobar_is_42() {
this.instance.SetFoobar( 42 );
}
public class GetAnswer : When_foobar_is_42
{
private Int32 result;
public GetAnswer() {
this.result = this.GetAnswer();
}
public void should_return_42() {
Assert.AreEqual( 42, result );
}
}
}
}
which will give me following output in my test runner:
MyClassSpecification+When_foobar_is_42+GetAnswer
should_return_42
I've been down the two roads you describe in your question as well as a few other... Your first alternative is pretty straight forward and easy to understand for most people. I personally like the BDD style (your second example) more because it isolates different contexts and groups observations on those contexts. Th only real downside is that it generates more code so starting to do it feels slightly more cumbersome until you see the neat tests. Also if you use inheritance to reuse fixture setup you want a testrunner that outputs the inheritance chain. Consider a class "An_empty_stack" and you want to reuse it so you then do another class: "When_five_is_pushed_on : An_empty_stack" you want that as output and not just "When_five_is_pushed_on". If your testrunner does not support this your tests will contain redundant information like: "When_five_is_pushed_on_empty_stack : An_empty_stack" just to make the output nice.
i vote for calling the test case class: EmployeeReaderTestCase and calling the methods() like http://xunitpatterns.com/Organization.html and http://xunitpatterns.com/Organization.html#Test%20Naming%20Conventions
Description for Assert.Equals() from the MSDN Documentation:
Do not use this method.
That's it, the full explanation. Uh.. ok, but then ... why is it there?
Is it a deprecated method from an earlier version of the framework? Something that's supposed to be used only by other Microsoft Assemblies?
It just makes me want to use it all the more knowing I'm not supposed to. ;-)
Does anyone know?
.Equals is inherited from object. It's listed as "Do not use this method" so users won't confuse it with the AreEqual method.
All objects in .NET derive from Object.
Object has a .Equals() method.
Apparently the .Equals() method for this particular object doesn't do anything useful, so the docs are warning you that it doesn't do anything useful.
It was changed in 2008 (Maybe SP1) to fail a test when called, so that people who were using it by accident were told they really shouldn't be using it.
Assert.Equals, just like its based class method Object.Equals, is perfectly useful for comparing objects. However, neither method is useful for stand-alone detection and reporting or errors in unit testing, since Object.Equals returns a boolean rather than throws if the values are not equal. This is a problem if used like this in a unit test:
Assert.Equals(42, ComputeMeaningOfLife());
Aside from the problem of this unit test possibly running too long :-), this test would silently succeed even if the Compute method provides the wrong result. The right method to use is Assert.AreEqual, which doesn't return anything, but throws an exception if the parameters aren't equal.
Assert.Equals was added so code like in the sample above doesn't fall back to Object.Equals and silently neuter the unit test. Instead, when called from a unit test, Assert.Equals always throws an exception reminding you not to use it.