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.
Related
Suppose we have a function add() as below:
void add(int a, int b) {
int sum=a+b;
cout<<sum;
sendSumToStorage(sum);
}
This simple function adds to input values, prints the sum to the console and also sends it to some external storage (say, a file). This is how we ideally want it in the application (meaning, we don't want it to return anything).
For purposes of unit testing, is it valid (from a design perspective) if we modify the function signature so that it returns the sum? We could then have a test like:
bool checkAdd() {
int res=add(3, 4);
if(res==7) return true;
else return false;
}
Better yet, is this (returning a value) the only way we could unit test it? Is there some valid way in which we could unit test the add() function without changing the function signature?
A function like the one in your example is considered really bad practice.
Why do I say this?
Well, you have a method called add which adds two numbers AND calls something else. Basically your method doesn't do one thing, but two, which violates the Single Responsibility Principle.
This makes things much harder to test because you can't test just the add method in isolation.
So you would separate that into two methods with good names which reflect what they do and test them separately.
If you don't want to have issues with state between your methods, you will have to start returning results where it makes sense.
Ignoring the fact that this example has a bad desing.
For cases like this, when you want to check some internal behaviour instead of API you should rather try using some testing libraries like gtest and gmock.
It allows you to describe more sophisticated expectations than just function result.
For example you can set expectation that some method will be called during code execution using EXPECT_CALL macro.
More details here:
https://github.com/google/googletest/blob/master/googlemock/docs/ForDummies.md
Answering your question, it's always a bad practice to modify any part of tested code for the purpose of testing. In that case you are not longer testing production code. As it was suggested before it's better to split the functionality into smaller parts and test them isolated.
Changing the design of code to improve testability is very common and generally considered as a good practice. Obviously, not all such changes are necessarily real improvements - sometimes better solutions exist.
In your case, the code is difficult to test because it combines computations (the addition) with interactions with depended-on components (output and storing data). In your case (as Andrei has pointed out) the function also violates the SRP, but mixing computations and interactions generally makes testing more difficult, even in cases where the SRP is not violated.
I understand, you would change the function such that it will return the computed value in addition to printing it and writing it to the storage. This will allow you to test the computational part of the function. The function will then, however, only be partially tested. And, the purpose of the function will be further obfuscated.
If instead you split the function into one function doing the computation and one doing the interactions, you can thoroughly test the first with unit-testing, and use integration-testing for the other. Again, the usefulness of this approach is independent of whether the code violates the SRP or not.
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);
I am wondering if I should unit test functions that have no control flow. This functions take some input, call a sequence of 5/6 other functions, then return some output.
Testing them seems a waste of time, since I don't see what I would be testing exactly. The other functions called already have unit test for them.
The main drawback for me is that I don't know what the output should be a priori, I would need to call the same functions in the test scripit to see if the results coincide; and then what am I testing? That the test function and the actual function have the same lines in the same order?
Thanks for any insight
Note: Same as last question, if you think it's primarily opinion based reformulate as "According to the principles advocated in Art of Unit Testing, should i unit test functions with no control flow?"
Short answer: yes, of course you do!
Long answer: how a method does something is in the end "implementation" detail. In that sense: you should not care at all if a method is using a switch, some if/elses, a loop, or just calls other methods in sequence.
Instead, you should understand the contract that your method provides: which input it takes; and what comes out of it (depending on the inputs maybe).
That is what you focus on: creating a setup where your method can run; to then check if the method upholds that contract.
Example:
public void foo(Bar bar) {
FooBar fooBar = bar.wobbel();
fooBar.throttle();
fooBar.rattle(this.someField);
}
that code above doesn't contain any control flow statements. But still, there are various points in there where things could go wrong (for example NullPointerExceptions). Don't you think it would be better to catch those using unit tests?
Not sure how I should be asking the question, but when I define my mock objects, and somewhere in the code it attempts to cast it to a different type the test throws me
$Proxy6 cannot be cast to ...
How does one solve this problem?
Does this class really need to be mocked? I usually mock services and use concrete classes for value types passed in.
One thing you can do is outlined here: define an interface in your test.
If it really needs to be mocked and you can't do the above you could provide your own implementation which does what you want the mock to do e.g. records values passed in, methods called, returns the values you want etc. and assert what you need at the end - that might be a lot of work though.
Lastly, is this pointing you towards some unidentified interfaces in your design or that the code under test needs some refactoring?
As always, the test is telling you something about your design. Why is the code trying to cast the object? Could you give us more detail?
Should we be testing values that we already know the answer to?
If a value is important enough to be a dedicated hard code value then should should it be important enough of to change a test at the same time as the value? or is this just overkill?!
If by “hardcoded properties” you mean something like this (in Java):
int getTheAnswer() {
return 42;
}
Then you need to ask yourself—why not make it a constant? For example,
static final int THE_ANSWER = 42;
In such a case, you don’t need to unit-test it.
In all other cases, you should consider unit testing.
More context is required to answer your question. It just depends. Is your getXXX method called from another method that is under test? If so, then it's already tested. If not, what is the client doing? Does the method even need to exist?
If you were developing your code using TDD, then your unit test is what would have created the hardcoded property in the first place.
No, but a better question is why are you hardcoding values? I know sometimes you have system-wide config settings that rarely (or never) change, but ideally, even those should be configurable and so should be tested. Values that will NEVER change should still be accessed via well-named constants. If your system is still in early development, maybe you haven't built those components yet, so don't worry about testing them - yet. ;)
Hmm Ok I guess the exceptions might be math or physics constants.
Should we be testing values that we already know the answer to?
How do you know that? Someone might have changed the code, and as a regression, it returns something else now.
If those values are part of the public API you should test them.
And you should test them against the literal value, not a constant defined by the program you are testing (because those could have been changed in error).
// good
assertEquals( "Number", myClass.getType(1234));
assertEquals( "Number", MyClass.TYPE_NUMBER);
// not so good
assertEquals( MyClass.TYPE_NUMBER, myClass.getType(1234));
Apart from obvious points from other answers:
You might want to add also, an integration test to verify that your hardcoded values actually works and plays well with other components.
Sometimes you do needs to hard code values, i.e. when implementing interfaces that asks for a capability tests, something like
interface IDecoder { // in C#
bool SupportStreaming { get; }
}
Of course, when implementing the IDecoder interface above, you'd have to hard code a value for the SupportStreaming property.
But the important question would of course not be Weather the it returns the hardcoded value? but Weather the hardcoded value actually is the correct value? which is only relevant when doing integration testing and/or testing other units/methods that depends on the value.
I personally don't bother with testing anything that's declarative.