writing mock test case for log methods - java

public void logTimeTaken(String label, long estimatedTime, int size, boolean isDebug)
{
String out = label + " took " +
TimeUnit.MILLISECONDS.convert(estimatedTime, TimeUnit.NANOSECONDS)
+ " milliseconds for " + size + " events!";
if (isDebug) {
logger.debug(out);
} else {
logger.info(out);
}
}
I'm unable to write mockit here any one know help me in this..
test code here..
#Mock
EventUtility event;
#Test
public void getLogTimeTaken_checkBooleanTrue() {
doNothing().when(event).logTimeTaken("Corner Stone", 1000, 100, true);
eventUtil.logTimeTaken("Corner Stone", 1000, 100, true);
verify(event).logTimeTaken("Corner Stone", 1000, 100, true);
}
I test this code but i'm getting exception ,I don't know it is correct way or not and below is the exception
Exception ::Wanted but not invoked: event.logTimeTaken( "Corner
Stone",1000,100,true);
-> at com.wf.cornerstone.datacontrols.util.EventUtilityTest.getLogTimeTaken_checkBooleanTrue(EventUtilityTest.java:244)
Actually, there were zero interactions with this mock.
at com.wf.cornerstone.datacontrols.util.EventUtilityTest.getLogTimeTaken_checkBooleanTrue(EventUtilityTest.java:244)
can you help me this ..

Related

Project reactor - not able to use fallback method

I'm new to reactive programming. I was playing around with fallback methods in case of an error scenario. For this, I referred to this doc https://projectreactor.io/docs/core/release/reference/index.html#_fallback_method and created a sample code.
public static void main(String[] args) {
Flux.just("key1", "key2")
.flatMap(k -> callExternalService(k)
.doOnError(e -> System.out.println("Error scenario"))
.onErrorResume(e -> getFromCache(k)))
.subscribe(value -> System.out.println("value = " + value),
error -> System.out.println("error = " + error));
}
private static Mono<String> callExternalService(String input) {
if(input.equals("key2")) throw new RuntimeException("Mocking the exception");
return Mono.just(input + " - " + LocalDateTime.now());
}
private static Mono<String> getFromCache(String input) {
return Mono.just(input + " ^^ " + LocalDateTime.now());
}
Based on whatever I referred so far, doOnError should print the message in case of the ERROR scenario and onErrorResume should fall back to the other method. But I didn't see the expected outcome->
value = key1 - 2022-05-18T15:58:36.364949
error = java.lang.RuntimeException: Mocking the exception
Please correct me if I'm missing anything.

Unable to write Mockito test case for my void method

I need to test this code with Mockito (JUnit):
public class Calculation {
public void logTimeTaken(String label, long estimatedTime, int size, boolean isDebug) {
String out = label + " took " + TimeUnit.MILLISECONDS.convert(estimatedTime, TimeUnit.NANOSECONDS) + " milliseconds for " + size + " events!";
if (isDebug) {
System.out.println(out);
} else {
System.out.println(out);
}
}
}
I search so many examples google but still not getting any idea.
You can configure System with an instance of PrintStream which you can then assert against after invoking Calculation.logTimeTaken.
Here's an example:
#Test
public void canLogTimeTaken() {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
PrintStream out = new PrintStream(bout);
System.setOut(out);
Calculation sut = new Calculation();
sut.logTimeTaken("label", 20 , 2, false);
assertEquals("if isDebug is false label took 0 milliseconds for 2 events!\n", bout.toString());
}
Note: there is no need for Mockito here, this is just vanilla JUnit, no mocking.
But, it might be a better design to refactor logTimeTaken into two distinct aspects:
Deriving the log message
Logging that message
For example:
public String createTimeTakenMessage(String label, long estimatedTime, int size, boolean isDebug) {
return label + " took " + TimeUnit.MILLISECONDS.convert(estimatedTime, TimeUnit.NANOSECONDS) + " milliseconds for " + size + " events!";
}
public void logTimeTaken(String message) {
System.out.println(message);
}
Then testing createTimeTakenMessage is trivial and you might even choose not to test logTimeTaken at all since all it does is invoke a System method. Or, perhaps you would hide the 'log action' behind an interface with an implementation using System.out now and perhaps, later, other implementations using a formal logging framework such as Logback.

How can I ignore extra arguments with jargo?

I'm trying to allow jargo to ignore any amount of "junk-be-here" strings. How can I do that? This is the code I've come up with:
#Test
public void testUsage() throws Exception
{
Argument<Integer> nrOfPotatoes = Arguments.integerArgument("-n").build();
ParsedArguments parsedArguments = CommandLineParser.withArguments(nrOfPotatoes).parse("-n", "123", "junk-be-here");
int potatoesToPlant = parsedArguments.get(nrOfPotatoes);
System.out.println("Hold on, planting " + potatoesToPlant + " potatoes");
}
But I get:
se.softhouse.jargo.ArgumentExceptions$UnexpectedArgumentException: Unexpected argument: junk-be-here, previous argument: 123
at se.softhouse.jargo.ArgumentExceptions.forUnexpectedArgument(ArgumentExceptions.java:299)
at se.softhouse.jargo.CommandLineParserInstance.getDefinitionForCurrentArgument(CommandLineParserInstance.java:329)
at se.softhouse.jargo.CommandLineParserInstance.parseArguments(CommandLineParserInstance.java:262)
at se.softhouse.jargo.CommandLineParserInstance.parse(CommandLineParserInstance.java:234)
at se.softhouse.jargo.CommandLineParserInstance.parse(CommandLineParserInstance.java:228)
at se.softhouse.jargo.CommandLineParser.parse(CommandLineParser.java:224)
at
.....
You can use an indexed argument (by specifying no names to the argument), and set variableArity (any amount of arguments is allowed).
#Test
public void testUsage() throws Exception
{
Argument<List<String>> junk = Arguments.stringArgument().variableArity().build();
Argument<Integer> nrOfPotatoes = Arguments.integerArgument("-n").build();
ParsedArguments parsedArguments = CommandLineParser.withArguments(junk, nrOfPotatoes).parse("-n", "123", "junk-be-here");
int potatoesToPlant = parsedArguments.get(nrOfPotatoes);
System.out.println("Hold on, planting " + potatoesToPlant + " potatoes");
System.out.println("Junk:" + parsedArguments.get(junk));
}
This prints:
Hold on, planting 123 potatoes
Junk:[junk-be-here]

Cucumber reports values inside code

Is there some way to get these cucumber report values inside code in some variables?
For example:
int scenariosRun = cucumber.getScenarios(); // 8
int scenariosPassed = cucumber.getScenariosPassed(); // 8
Yes, you can get current scenario details in the after/before hook as given below,
#Before
public void before(Scenario scenario) {
System.out.println("------------------------------");
System.out.println("Starting - " + scenario.getName());
System.out.println("------------------------------");
}
#After
public void before(Scenario scenario) {
System.out.println("------------------------------");
System.out.println(scenario.getName() + " Status - " + scenario.getStatus());
System.out.println("------------------------------");
}

Stopping and removing a task from ScheduledExecutorService

I know that I can throw an exception to suppress further executions of task that has been scheduled for repeated execution inside a ScheduledExecutorService (see this question).
I also know that I can setRemoveOnCancelPolicy(true) to make sure cancelled tasks are removed from the queue.
My questions are: Is the task actually removed from the scheduler also when I throw an exception from within it? Does this happen by implicitly cancelling the future? If yes, does this mean that setRemoveOnCancelPolicy() also bears on this case?
Couldn't find anything in the Javadocs.
I was wondering the same, couldn't find anything in the docs, so I tried it out. Observation:
Throwing a RuntimeException marks the future as done, not cancelled.
The Runnable is removed from the scheduler's queue, regardless of setRemoveOnCancelPolicy().
Try it out yourself:
public class SchedulerTest {
protected final Logger log = LoggerFactory.getLogger(this.getClass());
#Test
public void schedulerExecutionException() throws Exception {
log.info("Test: schedulerExecutionException");
ScheduledThreadPoolExecutor sched = new ScheduledThreadPoolExecutor(2);
sched.setRemoveOnCancelPolicy(true);
ScheduledFuture future1 = sched.scheduleAtFixedRate(new Runnable() {
int counter = 0;
#Override
public void run() {
log.info("Runnable 1: "+ ++counter);
if (counter >= 2) {
log.info("Runnable 1: BOOOM");
throw new RuntimeException("boom");
}
}
}, 1, 1, TimeUnit.SECONDS);
ScheduledFuture future2 = sched.scheduleAtFixedRate(new Runnable() {
int counter = 0;
#Override
public void run() {
log.info("Runnable 2: "+ ++counter);
}
}, 1, 1, TimeUnit.SECONDS);
long cutoff = new Date().getTime() + 6000;
while (new Date().getTime() < cutoff) {
log.info("Scheduler Queue size: "+ sched.getQueue().size());
log.info("Future 1: is "+ (future1.isCancelled() ? "" : "not ") +"cancelled, is "+ (future1.isDone()? "" : "not ") +"done");
log.info("Future 2: is "+ (future2.isCancelled() ? "" : "not ") +"cancelled, is "+ (future2.isDone()? "" : "not ") +"done");
Thread.sleep(1000);
}
assertEquals(sched.getQueue().size(), 1);
future2.cancel(true);
log.info("Scheduler Queue size: "+ sched.getQueue().size());
log.info("Future 1: is "+ (future1.isCancelled() ? "" : "not ") +"cancelled, is "+ (future1.isDone()? "" : "not ") +"done");
log.info("Future 2: is "+ (future2.isCancelled() ? "" : "not ") +"cancelled, is "+ (future2.isDone()? "" : "not ") +"done");
assertEquals(sched.getQueue().size(), 0);
sched.shutdownNow();
}
}

Categories

Resources