I have a method as follows
public class ClientClass {
public void clientMethod() {
while(true){
doSomethings.....
}
}
}
I am trying to test using mockito. I am able to make the call to clientMethod, but since there is a while(true) inside clientMethod, the call never returns and I never reach to my assert statements which (of course) occur after clientMethod() invocation.
Is there a way to stop the loop after one loop iteration from my test case?
Technicaly you can't break the infinite loop in test without throwing an exception from inside it. If there is something inside the loop you can mock, then it may produce an exception for you.
When you're finding yourself in situation like this, when awkward workarounds are necessary for testing, then it's time to stop and think about the design. Non-testable code is generaly ill-maintainable and not very self-explanatory. So my advice would be to get rid of infinite loop and introduce an appropriate loop condition. After all, no application will live forever.
If you're still convinced that endless loop is the best way to go here, then you can perform a slight decomposition to make things more testable:
public class ClientClass {
// call me in production code
public void clientMethod() {
while(true){
doSomethings();
}
}
// call me in tests
void doSomethings(){
// loop logic
}
}
This was a source of a little frustration to me... because I like to start off the most sophisticated of GUI apps with a console handler.
The language I'm using here is Groovy, which is a sort of marvellous extension of Java, and which can be sort of mixed in with plain old Java.
class ConsoleHandler {
def loopCount = 0
def maxLoopCount = 100000
void loop() {
while( ! endConditionMet() ){
// ... do something
}
}
boolean endConditionMet() {
loopCount++
loopCount > maxLoopCount // NB no "return" needed!
}
static void main( args ) {
new ConsoleHandler().loop()
}
}
... in a testing class (also in Groovy) you can then go
import org.junit.contrib.java.lang.system.SystemOutRule
import org.junit.contrib.java.lang.system.
TextFromStandardInputStream.emptyStandardInputStream
import static org.assertj.core.api.Assertions.assertThat
import org.junit.Rule
import static org.mockito.Mockito.*
class XXTests {
#Rule
public SystemOutRule systemOutRule = new SystemOutRule().enableLog()
#Rule
public TextFromStandardInputStream systemInMock = emptyStandardInputStream()
ConsoleHandler spyConsoleHandler = spy(new ConsoleHandler())
#Test
void readInShouldFollowedByAnother() {
spyConsoleHandler.setMaxLoopCount 10
systemInMock.provideLines( 'blah', 'boggle')
spyConsoleHandler.loop()
assertThat( systemOutRule.getLog() ).containsIgnoringCase( 'blah' )
assertThat( systemOutRule.getLog() ).containsIgnoringCase( 'boggle' )
The beautiful thing that's happening here is that simply by declaring maxLoopCount the language automatically creates two methods: getMaxLoopCount and setMaxLoopCount (and you don't even have to bother with brackets).
Of course the next test would be "loop must exit if a user enters Q" or whatever... but the point about TDD is that you want this to FAIL initially!
The above can be replicated using plain old Java, if you must: you have to create your own setXXX method of course.
I got stuck in this because I was calling same method from inside the method by mistake.
public OrderEntity createNewOrder(NewDepositRequest request, String userId) {
return createNewOrder(request, userId);
}
Related
String color1 = moreColors.get(0);
String color2 = moreColors[0];
System.assertEquals(color1, color2);
// Iterate over a list to read elements
for(Integer i=0;i<colors.size();i++) {
// Write value to the debug log
System.debug(colors[i]);
}
I am learning Apex and just started what is meaning of line System.assertEquals(color1, color2); and what is mean by debug log here?
System.assert, System.assertEquals, System.assertNotEquals. I argue these are three of the most important method calls in Apex.
These are assert statements. They are used in testing to validate that the data you have matches your expectations.
System.assert tests an logical statement. If the statement evaluates to True, the code keeps running. If the statement evaluates to False, the code throws an exception.
System.assertEquals tests that two values are equal. If the two are equal, the code keeps running. If they are not equal, the code throws an exception.
System.assertNotEqual tests that two values are not equal. If the two are not equal, the code keeps running. If they are equal, the code throws an exception.
These are critical for completing system testing. In Apex Code, you must have 75% line test coverage. Many people do this by generating test code that simply covers 75% of their lines of code. However, this is an incomplete test. A good test class actually tests that the code does what you expect. This is really great to ensure that your code actually works. This makes debugging and regression testing far easier. For example. Lets create a method called square(Integer i) that squares the integer returned.
public static Integer square( Integer i ) {
return i * i;
}
A poor test method would simply be:
#isTest
public static void test_squar() {
square( 1 );
}
A good test method could be:
#isTest
public static void test_square() {
Integer i;
Integer ret_square;
i = 3;
ret_square = square( i );
System.assertEquals( i * i; ret_square );
}
How I would probably write it is like this:
#isTest
public static void test_square() {
for( Integer i = 0; i < MAX_TEST_RUNS; i++ ) {
System.assertEquals( i*i, square( i ) );
}
}
Good testing practices are integral to being a good developer. Look up more on Testing-Driven Development. https://en.wikipedia.org/wiki/Test-driven_development
Line by Line ...
//Get color in position 0 of moreColors list using the list get method store in string color1
String color1 = moreColors.get(0);
//Get color in position 0 of moreColors list using array notation store in string color2,
//basically getting the same value in a different way
String color2 = moreColors[0];
//Assert that the values are the same, throws exception if false
System.assertEquals(color1, color2);
// Iterate over a list to read elements
for(Integer i=0;i<colors.size();i++) {
// Write value to the debug log
System.debug(colors[i]);//Writes the value of color list ith position to the debug log
}
If you are running this code anonymously via the Developer console you can look for lines prefixed with DEBUG| to find the statements, for e.g.
16:09:32:001 USER_DEBUG 1|DEBUG| blue
More about system methods can be found at https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_system.htm#apex_System_System_methods
I'm looking for a clean way to translate complex logical conditions with if and else statements that lead to different actions, into lambdas and streams.
Suppose I have this code:
List<OuterData> result = new LinkedList<>();
for (Outer outer : getOutersFromSomewhere()) {
OuterData outerData = new OuterData();
if (outer.isImportant()) {
doImportantAction(outer, outerData);
} else if (outer.isTrivial()) {
doTrivialAction(outer, outerData);
} else {
doDefaultAction(outer, outerData);
}
for (Inner inner : outer.getInners()) {
if (inner.mustBeIncluded()) {
InnerData innerData = new InnerData();
if (inner.meetsCondition1()) {
doAction1(inner, innerData, outer, outerData);
} else if (inner.meetsCondition2()) {
doAction2(inner, innerData, outer, outerData);
} else {
doDefaultAction(inner, innerData, outer, outerData);
}
outerData.add(innerData);
}
}
result.add(outerData);
}
return result;
This is simplified from real code I have. I know it can be optimized and refactored, i.e. I could move inner for to a private method. I'd like to know how to translate the if, else if and else parts to streams and lambdas.
I know how to translate the skeleton of this example. I'd use List.stream(), Stream.map(), Stream.filter(), Stream.collect() and Stream.peek(). My problem is with conditional branches only. How can I do this translation?
One first obvious way is to stream your elements, filter them according to the needed criteria, and then applying the action on each remaining element. This also makes the code much cleaner:
List<Outer> outers = getOutersFromSomewhere();
outers.stream().filter(Outer::isImportant)
.forEach(outer -> doImportantAction(outer, outerDate));
outers.stream().filter(Outer::isTrivial)
.forEach(outer -> doTrivialAction(outer, outerDate));
// default action analog
Caution: This only works if the important, the trivial, and the default elements form a partition. Otherwise it is not equivalent to your if-else-structure. But maybe this is intended anyway ...
The main problem with this approach: It is not very good OOP. You are querying the objects in order to make a decision. But OOP should be "tell, don't ask" as much as possible.
So another solution is to provide a consuming method in your Outer class:
public class Outer {
...
public void act(OuterData data, Consumer<Outer> importantAction,
Consumer<Outer> trivialAction, Consumer<Outer> defaultAction) {
if (isImportant())
importantAction.accept(this, data);
else if (isTrivial())
trivialAction.accept(this, data);
else
defaultAction.accept(this, data);
}
}
Now you call it as simple as this:
List<Outer> outers = getOutersFromSomewhere();
outers.forEach(outer -> outer.act(...)); // place consumers here (lambdas)
This has a clear advantage: If you ever have to add a feature to your Outer class - let's say isComplex() - you have to only change the internals of that single class (and maybe resolve the compiler failure in other parts). Or maye you can add this feature in a backward compatible way.
The same rules can be applied to the Inner class and the iteration.
I have a Volcano class. It's purpose is to randomly spray lavaMass.
In the main class I have made it so that when my character hits the lava, everything is removed, and the deleteLava() function is called.
My problem is that with the deleteLava() function, my Volcano class stops making lava after a few 'deaths'.
Now i gets a little complicated to explain.
I found out that inside the deleteLava() function I should also remove the lavaMass from the array, for it to keep making lava no matter how many 'deaths'.
I used 'lavaSpray.shift();', and tried 'splice'..
And this worked! Except that it doesn't delete all the lavaMass, so everytime the character dies a few of the lavaMass objects keeps hanging around in the level, not moving. So after many 'deaths' there is a lot of lavaMass objects just standing still, not moving and not being deleted.
Here's the volcano class:
package {
import flash.display.MovieClip;
import flash.events.Event;
public class Volcano extends MovieClip {
var lavaSpray:Array = [];
var lavaNum:Number;
var world:World;
public function LavaThing() {
addEventListener(Event.ENTER_FRAME, makeLava)
}
public function deleteLava()
{
this.parent.removeChild(this)
for (var m = 0; m < lavaSpray.length; m++) {
if (lavaSpray[m].parent) {
lavaSpray[m].parent.removeChild(lavaSpray[m]);
}
}
}
function makeLava (e:Event)
{
lavaNum = Math.random()*70
if (lavaSpray.length<20)
{
if (lavaNum > 68.15)
{
var lavaMass = new LavaMass();
lavaSpray.push(lavaMass);
addChild(lavaMass);
lavaMass.scaleY = 0.5;
lavaMass.scaleX = 0.5;
lavaMass.x += 90;
lavaMass.y += Math.random()*30
lavaMass.y -= Math.random()*30
}
}
for each (lavaMass in lavaSpray)
{
lavaMass.x += 4;
if (lavaMass.parent && lavaMass.x > 800)
{
lavaMass.parent.removeChild(lavaMass);
lavaSpray.shift();
}
}
}
}
}
I hope someone knows what I'm talking about. Thanks in advance.
I put up a video with my problem:
https://www.youtube.com/watch?v=rYxYHB7rcgY&feature=youtu.be
I suspect the issues is:
you don't remove the ENTER_FRAME Event Listener when you delete the lava.
removing the child doesn't mean you deleted it's listener.
so you may remove all the lava , but still the ENTER_FRAME creates more !
you have to remove it your self.
so you have to add
removeEventListener(Event.ENTER_FRAME, makeLava)
as the first line at your function deleteLava()
....
or you may add
addEventListener(Event.REMOVED_FROM_STAGE, onRemoved)
and create onRemoved(e:Event){} function
then inside this function remove any listener you Added , including the ENTER_FRAME & the REMOVED_FROM_STAGE
try to read more about these subjects
Game Loop
entity system framework
Pool Object pattern
I may but links , but I prefer you Google them , and read from different resources - whatever the language they are explained with -
good luck
just for clarrifying your question.. You added the lavamass inside the volacano class? and you need to remove lavamass or volcano ? Dp you get any error during compilation? Also i encountered some thing like this when developing a shooting game, the removed bullets shows up after removing the bullerts. What i did was , i just added the bullets into a empty movieclip and removed the entire clip.
I have a property in my controller that I would like to test:
public List<SelectOption> exampleProperty {
get {
//Do something;
}
}
I am not sure how to cover this code in my test class. Any ideas?
There is direct way, just invoke the property from test method
List<SelectOption> temp = obj.method;
You may need to directly test your properties, especially if you use lazy initialization - a smart pattern for making code efficient and readable.
Here's a list example of this pattern:
Integer[] lotteryNumbers {
get {
if (lotteryNumbers == null) {
lotteryNumbers = new Integer[]{};
}
return lotteryNumbers;
}
set;
}
If you wanted full coverage of the pattern (which may be a good idea while you're getting used to it), you would need to do something like the following:
static testMethod void lotteryNumberFactoryText() {
// test the null case
System.assert(lotteryNumbers.size() == 0);
Integer[] luckyNumbers = new Integer[]{33,8};
lotteryNumbers.addAll(luckyNumbers);
// test the not null case
System.assert(lotteryNumbers == luckyNumbers);
}
First off, do you really want to have an attribute named "method"? Seems a helluva confusing. Anyway, to cover the code, just call
someObject.get(method);
But code coverage should be a side effect of writing good tests - not the goal. You should think about what the code is supposed to do, and write tests to check (i.e. assert) that it is working.
I have a method DoCleanUp(), which will ask user to proceed and then clear current workspace. It will return if user choose to cancel this process.
My question is, which signature is best to indicate a "cancel"?
bool DoCleanUp(); // return false to indicate canceled.
bool DoCleanUp(); // return true to indicate this method should be canceled.
void DoCleanUp(bool& cancel); // check parameter 'cancel' to see if this method was canceled.
UPDATE: As for the language, it's C++\CLI or C#.
UPDATE2: Now suppose I have to save a file in the DoCleanUp method. I'll prompt a dialog ask user whether to save/not save/cancel the file. Based on the answers, here is what I came up:
void DoCleanUp();
DialogResult AskToSaveFile(); // return yes/no/cancel
void DoCleanUp( bool saveFile );
Usage:
void DoCleanUp()
{
DialogResult result = AskToSaveFile();
if( result == DialogResult::Cancel ) return;
bool saveFile = (result == DialogResult::Yes) ? true : false;
DoCleanUp( saveFile );
}
Then by calling DoCleanUp(), you know user will have the opportunity to cancel;
By calling DoCleanUp(bool saveFile), you can control whether to save file without asking user.
Is that looks better?
This is a classic single responsibility problem.
The reason that you are unsure about the signature is that the method is doing 2 things.
I would create 2 methods:
bool CheckIfTheUserWantsToCancel()
void DoCleanUp()
EDIT
Based on the comments and edits to the question I would create a 3rd method:
void SaveFile()
The DoCleanUp would then first call CheckIfTheUserWantsToCancel, and then if not cancelled would call SaveFile.
IMHO this is much better than trying to remember that DoCleanUp with parameter false will save the file without asking the user, or was it the other way around?
Without more details I would say answer 1 is the best IMHO. Third is rather ugly since it requires more code for calling.
But maybe consider rewriting code to this
void CleanUp() {
switch (AskUser()) {
case ButtonOk: CleanUpDesk(); break;
case ButtonNo: break;
default:
case ButtonCancel: CancelCleanUpDesk(); break;
}
}
This seems to in the spirit of single responsibility. My code somehow breaks your problem into two steps: asking user and performing action.
I would use your 1 version.
bool DoCleanUp(); // return false to indicate canceled.
The assumption is, that it returns true when the cleanup is done. Returning false would indicate a 'Error' state. It might even make sense to return an int. In this case the convention usually is that 0 represents success and everything else is an error code.
Regardless of what you decide, document what your return values mean!
The confusing bit is the calling it DoSomething(), when it might not do anything. How about
if (QueryCleanup()) // boolean
DoCleanup(); // void
More verbose but clearer, even without seeing the declaration.
You should not use a boolean for statuses (or status messages). Create an Enum:
public Enum CleanupStatus
{
Ok = 0,
Cancel
}
This way it is more clear what the return value is ... and if you need to add more statuses, you can.
(This is all from Code Complete 2, you should read it if you haven't yet.)
You have two requests basically. The outer request is to create a new workspace. The inner request is to save the current workspace. You want to return true if the outer request continues and false if the outer request is aborted. The action of the inner request is not important to the outer request and so should be some kind of delegate/functor/closure.
Make a class to genericize this:
class YesNoCancel {
string question; // question to ask the user about the inner state
delegate doit; // function to call to
delegate dontdoit;
public:
YesNoCancel(string question, delegate doit, delegate dontdoit = null) {...}
bool run() {
switch (AskUser(question)) {
case ANSWER_YES: doit(); return true;
case ANSWER_NO: return true;
case ANSWER_CANCEL: if (dontdoit) dontdoit(); return false;
};
//usage
void NewWorkspace() {
if (m_workspace) {
YesNoCancel ync("Save current workspace?", saveworkspace);
if (!ync.run()) return;
}
// new workspace code
}
void CloseApp() {
YesNoCancel ync("Save current workspace?", saveworkspace);
if (ync.run()) ExitApplication();
}
I believe option three gives the most clarity. When you have the bool as a return type it is not immediately clear what it is used for.
I usually go with
bool DoCleanUp(); // Returns true if cancel
but mostly it depends on whether the calling code looks like this:
if (DoCleanUp()) {
// Do cancel up code
}
or:
if (DoCleanUp()) {
// Do non-cancel post clean up code
}
Basically I try to make my tests not have to use a ! or language equivilent as I find it hard to see.
I definitely would not do number 3.
I prefer the third signature, only because by looking at it (without any extra documentation), I can tell more about what the method does. I would call the argument something more explicit, like processCancelled, though.