How to add unit tests to Java project in intellij IDEA? - java

I want to create simple java project with JUnit, so for example I'm want to write an algorithm like merge sort or some Java class and create test class so I can make unit test for that class.
I've create the project with:
File -> New -> Project -> java -> next and setup the project name and
location
and I want to make the unit test for the class the I've created, and I've tried the following solotions :
solution 1 from IntelliJ IDEA dosc using the light bulb to create the test class
solution 2 using shortcut [ctrl + shift + t]
But I always endup with import static org.junit.Assert.*; cannot resolve symbol 'junit', I tried different unit test library end up the same way.
How to resolve this problem so I can make unit test class in this simple Java project?

You can use Gradle or Maven (my personal preference these days).
But the easiest way is to add the JUnit JAR to your project, write some tests, and execute them in IntelliJ.
Go to JUnit and download version 4.12 of the JAR. Put it in a folder /test-lib in your IntelliJ project.
Create a folder /src and add a package /model and a Java class Foo to it (I'll write you one).
Mark /src as a source root.
Create a folder /test and add a package /model and a Java class FooTest to it (I'll write that, too).
Mark /test as a test source root.
Right click on /test and tell IntelliJ to "Run All Tests".
IntelliJ will run all the tests and present the results in the Run window.
Here's the model class:
package model;
public class Foo {
private String value;
public Foo(String v) { this.value = v; }
public String toString() { return this.value; }
}
Here's the test class:
package model;
public class FooTest {
#Test
public void testToString() {
String expected = "Test";
Foo foo = new Foo(expected);
Assert.assertEquals(expected, foo.toString());
}
}

I'm not sure this is the best solutions but I manage to build the unit test use gradle and maven. like this :
create Java project :
File -> New -> Project -> Gradle -> choose only java-> fill the
groupId and ArtifactId-> choose use default gradle wrapper -> enter
project name and location ->finish
and from the root of the project
right click -> Add Framework Support -> choose maven.
from there I can create the class that I want and make the unit test using the solutions from the question [ctrl + shift +t] .

Related

Main class not found in project IntelliJ IDEA: Java Application

IntelliJ does not find a main class in my Java application project. The project was cloned from a git repository so had no run configuration. I go to Edit Configurations, add a new Application template, go to Main class: and it says "No matches found in project".
So, manually searching through the hierarchy I find the .java file that contains the main function but it will not accept it as the main class. I've pasted the file below to prove that it has the correct main function.
public class AdvanceWarsGameHandler implements IGame
{
private Image mImage;
private String mTitle;
public AdvanceWarsGameHandler()
{
mTitle = "Advance Wars Game";
mImage = new Image("/OffBrandCerealOopsAllCarries2-01.png");
}
//Game logic unrelated to graphics goes here
#Override
public void update(Game game, float deltaTime)
{
}
//Update, but for graphics
#Override
public void render(Game game, Renderer renderer)
{
renderer.drawImage(mImage, game.getInput().getMouseX(), game.getInput().getMouseY());
}
public static void main(final String args[])
{
//Creating and starting an instance of AdvanceWarsGameHandler
AdvanceWarsGameHandler advancewars = new AdvanceWarsGameHandler();
Game myGame = new Game(advancewars);
myGame.start();
}
public String getTitle()
{
return mTitle;
}
}
So the question is, why is the IntelliJ project not recognizing the main function in this file, or what is IntelliJ looking for as the "Main class" of an application?
Okay, hopefully this answer will help others who are unfamiliar with IntelliJ IDEA.
The solution came in two parts
Part 1: Missing compilation directory.
Since I did not create the project from new and instead I cloned a Git repository, there was no default compilation directory set up.
To access this in IntelliJ IDEA go to File -> Project Structure -> Project and set the "Project compiler output" so the project can actually compile.
Part 2: Setting up the modules
The original project was created in Eclipse which has packages. In order to get those packages to work in IntelliJ, I had to go to the Modules tab of the Project Structure menu and set my src and res folders as Source and Resource Folders. This allowed IntelliJ to find the main() function in my class and the program ran as expected.
This solved my problem though if any of you IntelliJ users out there can see anything bad about what I did to get it working, please comment.

Write Unit Test In Different Package Calling Private/Protected Methods Using Intellij

I realize this question has been asked before here -> How to create a test directory in Intellij 13?
However, the answer is not working for me and I can't figure out why...
Intellij Version:
IntelliJ IDEA 2016.1.4
Build #IC-145.2070, built on August 2, 2016
JRE: 1.8.0_77-b03 x86
JVM: Java HotSpot(TM) Server VM by Oracle Corporation
MyApp.java
package main.java.com.simpleproject;
public class MyApp {
private int updNum;
public MyApp(int givenNum){
this.updNum = givenNum;
}
private void updateNumPlusTwo(){
this.updNum += 2;
}
protected int getUpdatedNum(){
return this.updNum;
}
}
MyAppTest.java
package test.java.com.simpleproject;
import main.java.com.simpleproject.MyApp;
public class MyAppTest {
public static void main(String[] args) {
MyApp app = new MyApp(4);
app.getUpdatedNum();
app.updateNumPlusTwo();
}
}
The package/directory tree:
The Issue:
What I have tried:
Anyone have any idea how to get this to work?
Your sources directories and packages are wrong.
You have chosen the Maven default sources directories structure of src/main/java for production code, and src/test/java for test code. You should declare both directories as source folders in IntelliJ (Project Structure -> Modules -> select the folders and click on Sources for src/main/java and Tests for src/test/java)
Your packages should be the same: com.simpleproject. The problem is that you have declared 2 different packages (main.java.com.simpleproject and test.java.com.simpleproject) that's why you cannot call a protected method.
It is not possible to call a private method, from the same or different package. You have to use reflection for that. But preferably you should at least put your method protected or package default.
Your test should use JUnit, not a main method. Something like :
package com.simpleproject;
import static org.assertj.core.api.Assertions.assertThat;
public class Test {
#Test
public void shouldTestMyClass() {
// Given
int givenNum = 3;
// When
MyApp myApp = new MyApp(givenNum);
myApp.updateNumPlusTwo();
// Then (use AssertJ library for example)
assertThat(myApp.getUpdatedNum()).isEqualTo(5);
}
}

How to link feature and step definition in cucumber

I'm new to Cucumber java and had this problem in initial stages:
I'm not using MAVEN project for some reason. I just created a simple java project in eclipse.
I have my features under "src/dummy/pkg/features", and my implementation "StepDef.java" is under "src/dummy/pkg/features/implementation"
I have written step definitions for Given, When, and Then, but when I run my features file, it is unable to recognize the implementation. How do I link the features with step definitions?
create a class YourClass and it would look something like the below and run it as JUnit test.
#RunWith(Cucumber.class)
#CucumberOptions( monochrome = true,
features = "src/dummy/pkg/features/",
format = { "pretty","html: cucumber-html-reports",
"json: cucumber-html-reports/cucumber.json" },
glue = "your_step_definition_location_package" )
public class YourClass {
//Run this from Maven or as JUnit
}
When you run your Runner class then it will scan all the feature file mentioned within features options and load the them afterward all step definition within package started by text mentioned within glue options will get loaded.
For e.g.
#RunWith(Cucumber.class)
#CucumberOptions(
plugin = { "pretty","json:target/cucumberreports.json" },
glue = "stepDefinition",
features = "src/test/resources/TestCases/",
tags={"#onlythis"},
dryRun=false
)
public class RunTest {
}
Here all the feature file present within
src/test/resources/TestCases/
will get loaded
then all the stepdef within or it's subdirectory will get loaded
stepDefinition
and whenever your step from feature get run then cucumber will look for function corresponding to step's regex and function will run.
for e.g.
whenever step When User enters email id in src/test/resources/TestCases/Login.feature will run then cucumber will find its corresponding function in all stepdef classes
Login.feature
#LoginValidation
Feature: To smoke test functionalities of app
#Browser #ValidLogin
Scenario: Verify scenario in case of successful login
When User enters email id
And User enters password
Then User clicks on sign in button and able to sign in
And moment it will reach class in subdirectory of stepDefinition i.e. in
stepDefinition.ui.home.LoginPageStepDef.java cucumber will find function with #When("^User enters email id$") and will execute this function.
LoginPageStepDef.java
public class LoginPageStepDef {
LoginPage loginPage = new LoginPage(AttachHooks.driver);
private static Logger LOGGER = Logger.getLogger(LoginPageStepDef.class);
#When("^User enters email id$")
public void user_enters_email_id() throws Throwable {
//LoginPage.obj = loginPage;
loginPage.enterEmailId(ConfigManager.getProperty("UserName"));
}
}
You have to convert your project to Cucumber project. Right-click on your project from the Project Explorer > Configure > Convert as Cucumber Project.
Create a runner class something like this and you should be able to execute.
There is also no need to write step definitions manually, just create a feature file and run it, it will create a snippet of the step definition which can be used to create a step definition class:
A class file called Runnerclass is required to run the cucumber:
#RunWith(Cucumber.class)
#CucumberOptions(plugin={"pretty","html:format"},
features = "Features/name.feature",glue={"path where step definitions exist"})
public class RunnerClass {
}

How to call a class from another project in Eclipse?

I'm using Eclipse and I have two different projects: A and B.
In project A, I have a class classA where I need to call a method methodB() from a class classB contained in the project B, how can I do that?
I've tried adding the project B to project A build path, but still doesn't work.
Thanks.
You need to add another project in "Project" tab, or add class folder of the project in "Libraries" tab ie you may try to add project B to the Run configuration used by project A. Go to the menu Run -> Run configurations, ther you can add the project B in the tab 'classpath' of your run configuration.
Here's an example that you may find helpful:
Project_1 has the following class:
ClassProjectOne.java which consists of:
public class ClassProjectOne {
private int m_Age;
private final int AGE_INPUT = 15;
public ClassProjectOne() {
setAge(AGE_INPUT);
}
public int getAge() {
return m_Age;
}
private void setAge(int age) {
m_Age = age;
}
}
Project_2 has the following class:
ClassProjectTwo.java which consists of:
public class ClassProjectTwo {
public static void main(String[] args) {
ClassProjectOne t = new ClassProjectOne();
System.out.println(t.getAge());
}
}
In order for this to work, you must right click Project_2 and click on Properties. Then click on Java Build Path -> Add... -> Select Project_1 -> OK. This sets a Java Build Path.
If your class is static there is no need to initialize a new instance of it.
Hope this helps.
I've just done what you're trying to do. I called my first project 'project1'. In this projects i have a package called 'package1' which in turn contains a class called 'Class1' containing a (public) static method called 'staticMethod'. I called my second project 'project2' with a class 'Class2' in 'package2'. I added project1 to the build path of project2 and then inserted the statement import package1.Class1 at the beginning of the class Class2.
Put the Project B on the Build path, then do a Clean project from Project Menu option and then use it.
Click in "A" --> Properties --> Build Path --> Projects ---> Add the Project ---> Ok

Simplest way to unit test an android library application?

Sorry if this is a bit of a vague question, however im struggling to find a single solid example on how to do unit testing (isolated testing) with Android...
Here is an example of what i'm wanting to achieve:
// Some class
class Calculator
{
public int Add(int a, int b) { return a+b; }
}
// Simple test
import org.junit.Assert;
import org.junit.Test;
class CalculatorTests
{
#Test
public void should_add_numbers_correctly()
{
Calculator calculator = new Calculator();
int expectedResult = 5 + 5;
int actualResult = calculator.Add(5,5);
Assert.assertEqual(actualResult, expectedResult);
}
}
So one project contains models and logic, then another project contains tests for said library. There is no front end or UI, so I want to do the bare minimum to just be able to test that my methods all work in isolation.
As long as your "library" doesn't contain any references to resources in the Android SDK, there isn't anything more to this than regular unit testing. In your Eclipse workspace, say you have your main project MyAndroidLibProject, you simply create a new Java Project (e.g. MyAndroidLibProjectUnitTests). Inside here, you create ordinary unit tests referring to the Calculator class in your main project (just make sure that your main project is added to the build path of your test project).
You might also find some additional information in a similar question I asked myself earlier, as well as the answer to that question.
Updated with example:
import static org.junit.Assert.*;
import org.junit.Test;
public class SemesterTest
{
#Test
public void aNewSemesterShouldHaveANegativeId()
{
Semester semester = new Semester(2010, SemesterType.FALL);
assertEquals(-1, semester.getInternalId());
}
#Test
public void toStringShouldPrintSemesterTypeAndYear()
{
Semester semester = new Semester(2010, SemesterType.FALL);
assertEquals(SemesterType.FALL + " 2010", semester.toString());
}
#Test
public void equalityShouldOnlyDependOnSemesterTypeAndYear()
{
Semester aSemester = new Semester(2010, SemesterType.FALL);
aSemester.setInternalId(1);
Semester anotherSemester = new Semester(2010, SemesterType.FALL);
anotherSemester.setInternalId(2);
assertEquals(aSemester, anotherSemester);
}
}
The above is a test of my own Semester class (a simple data class representing a semester). Semester is located inside my android project MyMainProject (but the class itself doesn't contain any references to the Android SDK). SemesterTest is located inside my test project MyTestProject (an ordinary Java project), with both MyMainProject and MyTestProject being in the same workspace (and since SemesterTest has the same package name as Semester, I don't need any special import statement to reference Semester either). MyTestProject also has MyMainProject added to its build path (junit.jar is also added to the build path, but this happens automatically, at least in Eclipse I think).
So as you can see, this is nothing but a completely ordinary unit test (JUnit 4, just to have mentioned it). Hope this helps.

Categories