Comparing an array to a single string output using assertEquals in Java - java

So I would like to create a simple code that greets people according to the input.
The difficulity I have that I have no idea how to compare a simple string with an array, using arrayEquals (or any equivalent).
This is the way I have created the code - according to a previous project:
Test file:
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class test {
#Test
public void ShouldGreet() {
assertEquals("Hello, my friend.", new GreetPeople().greeter(""));
assertEquals("Hello, Bob.", new GreetPeople().greeter("Bob"));
}
}
Actual code:
import java.util.Arrays;
public class GreetPeople {
public String greeter(String[] names) {
if (Arrays.stream(names).count() == 1) {
return("Hello, " + names + ".");
}
return("Hello, my friend.");
}
}
Any kind of help is well appreciated!

The first patameter of greeter is an array:
assertEquals("Hello, my friend.", new GreetPeople().greeter(new String[]{""}));
assertEquals("Hello, Bob.", new GreetPeople().greeter(new String[]{"Bob"}));

Related

problem regarding my discord bot coded through jda

My bot is stuck printing the output. I check and there was no problem with the logical part as I used the sane logic to make a normal java program. Please help as it is stuck printing the output in discord and I do not know how to solve it.
I also added some unnecessary print functions to find out where the error was. To my surprise, it was just in printing the message which is unusual as I have made bots before and none of them had any errors to just "print" messages.
import javax.security.auth.login.LoginException;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.OnlineStatus;
import net.dv8tion.jda.api.entities.Activity;
public class rpsidnfp {
public static JDA jda;
public static void main(String args[]) throws LoginException {
jda = JDABuilder.createDefault("(my token here)").build();
core2 core2obj = new core2();
jda.addEventListener(core2obj);
}
}
The former was my main class.
And below is the core class as it contains all the functions.
package pack.rpsidnfp;
import java.util.Random;
//import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
public class core2 extends ListenerAdapter {
public static String prefix = "!";
public void onGuildMessageReceived(GuildMessageReceivedEvent event) {
String input = event.getMessage().getContentRaw();
String[] options = {"rock", "paper", "scissors"};
Random robj = new Random();
int rnum = robj.nextInt(options.length);
System.out.println(rnum);
String conf = options[rnum];
event.getChannel().sendMessage(conf);
System.out.println(conf);
String same = prefix + conf;
String win = "congrats, you won!";
String lose = "lmao, you lost";
if(input.equals(same)) {
event.getChannel().sendMessage("we both kept the same thing");
}
else if(input.equals(prefix + options[0])) {
if(conf.equals(options[1])) {
event.getChannel().sendMessage(lose);
}
else if(conf.equals(prefix + options[2])) {
event.getChannel().sendMessage(win);
}
}
else if(input.equals(prefix + options[1])) {
if(conf.equals(options[0])) {
event.getChannel().sendMessage(win);
}
else if(conf.equals(options[2])) {
event.getChannel().sendMessage(lose);
}
}
else if(input.equals(prefix + options[2])) {
if(conf.equals(options[0])) {
event.getChannel().sendMessage(lose);
}
else if(conf.equals(options[2])) {
event.getChannel().sendMessage(win);
}
}
}
}
The sendMessage method returns a MessageAction. You need to call queue() on that RestAction instance.
Additionally, keep in mind that your bot receives its own messages so you should make sure it ignores those. You can add a if (event.getAuthor().isBot()) return; to the start of your listener method.
See Also:
Troubleshooting Guide: Nothing happens when using X
RestAction Guide
MessageListenerExample
JDA README

java : Identifier expected error when calling a void method from another class

So I've been trying to create a set of cards by defining them through their value then create one class per color. I have a method for creating a list of 13 cards from 2 to ace:
package test;
import java.util.*;
public class Cartes {
void liste_cartes(){
ArrayList liste_cartes = new ArrayList();
for(int i=2; i<15; i++) {
liste_cartes.add(i);
}
}
}
I've tried using this method in my color class !
package test;
import java.util.*;
public class Coeur {
Cartes cartes = new Cartes();
cartes.liste_cartes();
}
However I'm getting an <identifier expected> error on cartes.liste_cartes();. Relatively new to Java here, so any help is much appreciated.
For Java program,JVM first looks for main() to run the program. Try writing this:-
public class Coeur {
public static void main(String[] args) {
Cartes cartes = new Cartes();
cartes.liste_cartes();
}
}
Wrap cartes.liste_cartes(); in a method, like
public void dummyMethod(){ //should probably be your main method, if in your main class
cartes.liste_cartes();
}
Also, your ArrayList is of raw type. Make use of generics.
ArrayList<Integer> liste_cartes = new ArrayList<Integer>();

Can any of these examples work without using main? Please explain what problems do these examples have besides not having main

//Example 1:
package com.practice;
import java.util.ArrayList;
public class Testing1{
public Testing1()
{
super();
}
public ArrayList getFruits()
{
Arraylist <fruits> = new ArrayList <fruits>();
fruits.add("Orange");
fruits.add("Apple");
fruits.add("grape");
return fruits;
}
}
//Example 2:
package com.practice;
import java.util.ArrayList;
import java.util.List;
public class Testing1{
public Testing1()
{
super();
}
public List getFruits()
{
List <fruits> = new ArrayList<fruits>();
fruits.add("Orange");
fruits.add("Apple");
fruits.add("grape");
return fruits;
}
}
//I made typos on my original code
//contain mycontain; should have been a package name. I corrected that as //well.
//Corrected import java.util.Array.List; to import java.util.Array.List;
//I tried adding a string after List and ArrayList and still does not work //well
//I still don't understand.
//No, this is not a school assignment
//Maybe some can explain which one is correct or the two examples or both //need work? Thank you.
//
All programs need a main method. So no.

Importing ArrayList without IDE package

How can I count my messages? I have both classes in the same folder and I compile them in the terminal. I don't want to install an IDE and create a package.
My counting class:
import java.util.ArrayList;
public class countMessages{
public static void main(String args[]){
int count = messages.size();
}
}
My message containing class:
import java.util.ArrayList;
public class SampleDataBase {
public static ArrayList<String> messages;
static {
messages = new ArrayList<String>(12);
messages.add("A "+"message "+"with "+"pineapples.");
messages.add("A "+"message "+"with "+"grapes.");
messages.add("A "+"message "+"with "+"watermelons.");
}
}
To create a package just create a folder (name it for example myPackage) and put both classes in it. Also include a first line in both class files: package myPackage;. Remember to name the class files with the names of the classes.
To make your example work just change messages.size(); to SampleDataBase.messages.size();.
And you really should name the class CountMessages with a capital letter.
It's unclear what you are trying to do but what I think you are looking for is a main static method(?)
import java.util.ArrayList;
public class SampleDataBase
{
public static void main(String[] args)
{
ArrayList<String> messages = new ArrayList<>();
messages.Add("things...");
for(String message : messages)
{
System.out.println(message);
}
System.out.println("The number of messages is : " + messages.size());
}
}
in the terminal, to use:
Compile javac *.java
Execute java SampleDataBase
If you want to keep two classes, use this on your test class(that contains main method).
public class countMessages{
public static void main(String args[]){
// You must instantiate the other class
SampleDataBase sdb = new SampleDataBase();
// here you will get the total messages in your arrayList
int count = sdb.messages.size();
}

Testing private method using power mock which return list of Integers

I have a private method which take a list of integer value returns me a list of integer value. How can i use power mock to test it. I am new to powermock.Can i do the test with easy mock..? how..
From the documentation, in the section called "Common - Bypass encapsulation":
Use Whitebox.invokeMethod(..) to invoke a private method of an
instance or class.
You can also find examples in the same section.
Here is a full example how to do to it:
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.powermock.reflect.Whitebox;
class TestClass {
private List<Integer> methodCall(int num) {
System.out.println("Call methodCall num: " + num);
List<Integer> result = new ArrayList<>(num);
for (int i = 0; i < num; i++) {
result.add(new Integer(i));
}
return result;
}
}
#Test
public void testPrivateMethodCall() throws Exception {
int n = 10;
List result = Whitebox.invokeMethod(new TestClass(), "methodCall", n);
Assert.assertEquals(n, result.size());
}
Whitebox.invokeMethod(myClassToBeTestedInstance, "theMethodToTest", expectedFooValue);
When you want to test a private method with Powermockito and this private method has syntax:
private int/void testmeMethod(CustomClass[] params){
....
}
in your testing class method:
CustomClass[] params= new CustomClass[] {...}
WhiteboxImpl.invokeMethod(spy,"testmeMethod",params)
will not work because of params. you get an error message that testmeMethod with that arguments doesn't exist
Look here:
WhiteboxImpl class
public static synchronized <T> T invokeMethod(Object tested, String methodToExecute, Object... arguments)
throws Exception {
return (T) doInvokeMethod(tested, null, methodToExecute, arguments);
}
For arguments of type Array, PowerMock is messed up. So modify this in your test method to:
WhiteboxImpl.invokeMethod(spy,"testmeMethod",(Object) params)
You don't have this problem for parameterless private methods. As I can remember it works for parameters of type Primitve type and wrapper class.
"Understanding TDD is understanding Software Engineering"

Categories