Junit 5 (Jupiter) status of Test - java

hello every one i'm using Junit 5 Jupiter and i want to know after each test if it succeeded or fails and use the #AfterEach methods by each test result like if succeeded i will do something but if i fail i will do something else
can u help me out ..
seems that #rule work for Junit 4 not for Jupiter
package Example;
import static org.junit.Assert.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.platform.suite.api.SelectPackages;
import org.junit.rules.TestRule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.junit.runner.RunWith;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class SSJunit5 {
static WebDriver driver;
#BeforeAll
public static void setUpBeforeClass() throws Exception {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\david\\Desktop\\Documents\\Chrome Driver\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
}
#AfterAll
public static void tearDownAfterClass() throws Exception {
driver.quit();
}
#BeforeEach
public void setUp() throws Exception {
}
#AfterEach
public void tearDown() throws Exception {
}
#Rule
public TestRule watcher = new TestWatcher() {
#Override
protected void succeeded(Description description) {
System.out.println("Pass!");
}
#Override
protected void failed(Throwable e, Description description) {
ScreenShots.ScreenShot(driver, "SSafterSendKeys");
System.out.println("Fail!");
}
};
#Test
public void test() {
driver.get("https://www.google.com");
//ScreenShots.ScreenShot(driver, "webPageON");
driver.findElement(By.id("lsta-ib")).sendKeys("hello");
String expected = "asd";
String actual = "qwert";
assertEquals(expected, actual);
}
}

Related

Mockito Junit 5 Throw checked exception not working

I am trying to throw SQLException during a method call. But the exception is not thrown for some reason.
Error message
org.opentest4j.AssertionFailedError: Expected java.sql.SQLException to be thrown, but nothing was thrown.
at org.junit.jupiter.api.AssertThrows.assertThrows(AssertThrows.java:71)
at org.junit.jupiter.api.AssertThrows.assertThrows(AssertThrows.java:37)
at org.junit.jupiter.api.Assertions.assertThrows(Assertions.java:2952)
I would like the exception to be thrown when dropRun() is invoked
public interface RunRepository {
void dropRun(List<Integer> ids) throws SQLException;
}
Its Implementation
public class RunRepositoryImpl implements RunRepository{
#Override
public void dropRun(List<Integer> ids) throws SQLException {
//some piece of code
}
}
The Class I would like to test
public interface Project {
void purge() throws SQLException;
}
and its Implementation
public ProjectImpl implements Project{
#Override
public void purge() throws SQLException {
//some piece of code
try {
runRepository.dropRun(ids);
} catch (Exception e) {
LOGGER.error("Error purging completed runs.");
throw e;
}
}
}
Test class
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.willAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kfj.repository.RunRepository;
import com.kfj.service.Project;
import java.sql.SQLException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
#TestInstance(Lifecycle.PER_CLASS)
#ExtendWith(MockitoExtension.class)
public class ProjectImplTest {
private Project project;
#Mock
private RunRepository runRepository;
#BeforeEach
public void setUp() {
//some piece of code
project = new ProjectImpl(runRepository);
}
#Test
public void GIVEN_non_empty_completed_runs_WHEN_purge_is_invoked_THEN_dropRun_is_invoked()
throws SQLException {
//MOCK Trail 1 DIDN'T WORK
//doThrow(SQLException.class).when(runRepository).dropRun(any());
//MOCK Trail 2 DIDN'T WORK either
willAnswer(invocation -> {
throw new SQLException();
}).given(runRepository).dropRun(any());
//Then
assertThrows(SQLException.class, () -> project.purge());
}
}
I tried a couple of links, but no luck!. Any help would be highly appreciated. TIA.
Link1
Link2
I am facing the same issue, The following code doens't work.
JUnit fails with
org.mockito.exceptions.base.MockitoException:
Checked exception is invalid for this method!
Invalid: javax.xml.bind.JAXBException: aa
DocumentService documentService = mock(DocumentService.class);
#Test
#DisplayName("Returns 500 http status when we have an error calling the PFEL")
void handle_document_create_request_exception_in_service() {
willThrow(new JAXBException("aa")).given(documentService).generateDocument(any(DocumentCreateDto.class));
}
But if I replace the CheckedExcpetion with a RunTime exception, it works as expcected

In junit 4 #Beforeclass #Before and #After tests cases: wrong order of execution

I am trying to run some simple tests using Junit 4 library and am using #Before, #After, and #BeforeClass annotations. But the problem is #Before and #After are being executed before the #BeforeClass. why is that?
Code:
import junit.runner.Version;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class TestClass2
{
#BeforeClass
public static void before() throws Exception
{
System.out.println("Before class");
}
#Before
public void setUp() throws Exception
{
System.out.println("Before");
}
#After
public void tearDown() throws Exception
{
System.out.println("After");
}
#Test
public void name() throws Exception
{
System.out.println("Test");
System.out.println("JUnit version is: " + Version.id());
}
}
Output:
Before
Test
JUnit version is: 4.12
After
Before class
Process finished with exit code 0
Make sure you declare the #BeforeClass method as static, and using JUnit's annotation (not TestNG). A full code exmaple:
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* #author sainnr <p/>27.12.2017.
*/
public class TestClass {
#BeforeClass
public static void before() throws Exception {
System.out.println("Before class");
}
#Before
public void setUp() throws Exception {
System.out.println("Before");
}
#After
public void tearDown() throws Exception {
System.out.println("After");
}
#Test
public void name() throws Exception {
System.out.println("Test");
}
}
Output:
Before class
Before
Test
After
As per JUnit documentation: http://junit.sourceforge.net/javadoc/org/junit/BeforeClass.html.

junit error: initiallization error: coused an error: no rannable method

I am having this error while all my methods in this test are successful - all of them return true. Also tried to make boolean for each method call and use only one call for assertTrue(a && b && c && d && e).
I run the junit test in java - netbeans.
My junit code (first time using junit) is:
package redis_fast_algo;
import data_sets.FastSortAlgoData;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
public class FastSortAlgoStudyTest {
private DataMaker dataMake;
private final static boolean BEFORE_DELETE = false;
public FastSortAlgoStudyTest() {
}
#BeforeClass
public static void setUpClass() {
}
#AfterClass
public static void tearDownClass() {
}
#Before
public void setUp() {
dataMake = new DataMaker();
}
#After
public void tearDown() {
}
/**
* Test of study method, of class FastSortAlgoStudy.
*/
#Test
public void testStudy() throws Exception {
System.out.println("study");
FastSortAlgoData data = dataMake.getData(5);
FastSortAlgoStudy instance = new FastSortAlgoStudy(data);
FastSortAlgoTest testStudy = new FastSortAlgoTest(data);
testStudy.prepareForTest();
instance.study();
assertTrue(testStudy.testCheckFolderStudyCounter(BEFORE_DELETE));
assertTrue(testStudy.testCheckBodyPart(BEFORE_DELETE));
assertTrue(testStudy.testCheckTitlePart(BEFORE_DELETE));
assertTrue(testStudy.testCheckFoldersHistoryWithData(BEFORE_DELETE));
assertTrue(testStudy.testRemoveFolderHistory());
}
}

calling multiple methods within a method - selenium webdriver cross browser testing

I have a question with regards to calling multiple method using JUNIT. This is my test
package com.example.tests;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import org.testng.annotations.Test;
public class test {
private WebDriver _driver;
#Test
public void FFconfiguration() throws Exception {
System.out.println("Running FF");
_driver = new FirefoxDriver();
_driver.get("URL");
login();
setup();
_driver.quit();
}
public void login1()
{
}
public void setup()
{
}
}
My question is: Can I call both login() and setup() within the method FFConfiguration? If not what's the alternate solution...............
Yes, absolutely, you can do it. You can have tests like this:
#Test
public void testBuyingProcess(){
ShoppingUI shoppingPage = new ShoppingUI();
shoppingPage.login();
Assert.assertEquals(shoppingPage.getTitle(),"Welcome");
//....
}
And fill in the methods elsewhere even in different class. Few examples of methods used above:
public class ShoppingUI{
private WebDriver driver
public ShoppingUI(){
driver = new FirefoxDriver();
driver.get("http://my-test-site.com/buy-buy-buy.html");
}
public String getTitle(){
return driver.getTitle();
}
}

How to configure JUnit rules to apply to specific test

Is it possible to have a Junit rule only apply to specific tests? If so, how do I do that?
The code below exemplifies what I want to do: each time I have #Rule, I want the method below that to have the specific rule that has been annotated to run with it. I only want that rule to run with the corresponding test. I don't want anything other tests to be affected by the rule.
In this case, when I run these tests, I see that one of the tests the EmptyFileCheck, gives a File DNE does not exist, but I have used a separate annotation for that function, so I had thought that it would run with a different context, supplying the Empty, but instead DNE is till being used.
import static java.lang.System.in;
import static java.lang.System.setIn;
import static org.junit.Assert.fail;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import java.nio.channels.Pipe;
import static org.hamcrest.core.AllOf.allOf;
import org.hamcrest.Matcher;
import org.hamcrest.core.AllOf;
import static org.hamcrest.Matchers.*;
import org.hamcrest.text.StringContains;
import org.hamcrest.text.StringEndsWith;
import org.hamcrest.text.StringStartsWith;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.TextFromStandardInputStream;
import org.junit.runner.RunWith;
public class UnitTests {
private Mockery context = new Mockery() {{
setImposteriser(ClassImposteriser.INSTANCE);
}};
private main mn;
private InputStream oldIn;
private PrintStream oldOut;
private InputStream mockIn;
private InputStreamReader mockinputStream;
private PrintStream mockOut;
private BufferedReader reader;
private Expectations exp;
#Before
public void setMinimalMockingExpectations() throws IOException {
exp = new Expectations() {{ }};
mn = context.mock(main.class);
mockinputStream = context.mock(InputStreamReader.class);
oldIn = System.in;
oldOut = System.out;
mockIn = context.mock(InputStream.class);
mockOut = context.mock(PrintStream.class);
System.setOut(mockOut);
}
public void configureExpectations(boolean fileOrInput, boolean verbosity) {
exp.one(mockOut).println("Do you want to process standard (I)nput, or a (F)ile? I/F");
if (fileOrInput) { //it's a file
exp.one(mockOut).println("Enter filename: ");
} else { //it's not
}
}
#After
public void reset() {
System.setOut(oldOut);
}
#Rule
public final TextFromStandardInputStream FileNotFoundException
= new TextFromStandardInputStream("F\nDNE\n");
#Test(expected=FileNotFoundException.class)
public void EnsureFileCheckExists() throws IOException {
final String fileName = "DNE";
configureExpectations(true, false);
exp.one(mn).checkFile(fileName);
context.checking(exp);
mn.main(null);
}
#Rule
public final TextFromStandardInputStream FileReadAccessDenied
= new TextFromStandardInputStream("F\nUnderPriviledged\n");:w
#Test(expected=FileNotFoundException.class)
public void FileReadAccessDenied() throws java.io.FileNotFoundException {
final String fileName = "UnderPriviledged";
configureExpectations(true, false);
//exp.oneOf(mn).checkFile(with()); TODO: fix ME!
context.checking(exp);
mn.main(null);
}
#Rule
public final TextFromStandardInputStream EmptyFileCheck
= new TextFromStandardInputStream("F\nEmpty\n");
#Test
public void EmptyFileCheck() throws java.io.FileNotFoundException {
final String fileName = "Empty";
configureExpectations(true, false);
exp.one(mn).checkFile(fileName);
context.checking(exp);
mn.main(null);
}
}
You could have a setter in your Rule which is the first thing that gets called in the rule. Something like this, from ExpectedException:
// These tests all pass.
public static class HasExpectedException {
#Rule
public ExpectedException thrown= ExpectedException.none();
#Test
public void throwsNothing() {
// no exception expected, none thrown: passes.
}
#Test
public void throwsNullPointerException() {
thrown.expect(NullPointerException.class);
throw new NullPointerException();
}
#Test
public void throwsNullPointerExceptionWithMessage() {
thrown.expect(NullPointerException.class);
thrown.expectMessage("happened?");
thrown.expectMessage(startsWith("What"));
throw new NullPointerException("What happened?");
}
}
Any reason not to just take the code out of the #rule annotation and move it to the start of the test body?

Categories