Skip to content
Advertisement

JUnit5 test void method. Get org.opentest4j.AssertionFailedError: expected:

Don’t judge my code, I am beginner. In the future, I’ll refactor it.

I would like to ask for help writing JUnit5 unit tests.

I need to test my class Formatter

package com.*.text;

import com.*.math.Divider;
import com.*.model.Result;

/**
 * text sub package - for formatters
 */

public class Formatter {
    Result result;
    Divider divider;
    private int firstIndexPartialDividend = 0; // find the beginning of the number
    private int countSpace = 0; // space counter

    public Formatter(Result result) {
        this.result = result;
        this.divider = new Divider(result);
    }

    public void format() {
        // print the first row
        printFirstRow();
        String dividendText = Integer.toString(result.getDividend());
        for (int i = 1; i <= dividendText.length(); i++) {
            result.setFirstPartialDividend(Integer.parseInt(dividendText.substring(firstIndexPartialDividend, i)));
            // print the second row
            if (result.getFirstPartialDividend() >= result.getDivisor()
                    && firstIndexPartialDividend == 0) {
                countSpace = dividendText.length() - i;
                printSecondRow(result.getFirstPartialDividend());
                result.setRemainder(result.getFirstPartialDividend()
                        - result.getProduct());
                firstIndexPartialDividend = i;
                // To align the space in the next row.
                if (Integer.toString(result.getProduct()).length()
                        > Integer.toString(result.getRemainder()).length()
                        && result.getRemainder() > 0) {
                    countSpace = Integer.toString(result.getProduct()).length()
                            - Integer.toString(result.getRemainder()).length();
                } else {
                    countSpace = 0;
                }
                // print following row
            } else if (firstIndexPartialDividend > 0) {
                if (Integer.toString(result.getProduct()).length() / 2
                        == Integer.toString(result.getRemainder()).length()
                        && Integer.toString(result.getRemainder()).length() > 1) {
                    countSpace++;
                }
                int nextPartialDividend
                        = Integer.parseInt(Integer.toString(result.getRemainder())
                        + dividendText.substring(firstIndexPartialDividend, i));
                printFollowingRow(nextPartialDividend, dividendText, i);
                // print last row
                printLastRow(dividendText, i);
            }
        }
    }

    /**
     * printFirstRow method - print the first row of an application
     */
    public void printFirstRow() {
        System.out.printf("%d|%dn", result.getDividend(), result.getDivisor());
    }

    /**
     * printSecondRow method - print the second row of an application
     */
    public void printSecondRow(int firstPartialDividend) {
        divider.calculateProduct(firstPartialDividend);
        System.out.println(result.getProduct() + getSpace(countSpace) + "|"
                + (result.getQuotient()));
    }

    /**
     * printFollowingRow method - print all following row of an application
     * except for the last row
     */
    public void printFollowingRow(int nextPartialDividend, String dividendText, int i) {
        if (nextPartialDividend >= result.getDivisor()) {
            divider.calculateProduct(nextPartialDividend);
            alignFollowingRowSpace(nextPartialDividend, dividendText, i);
            result.setRemainder(nextPartialDividend - result.getProduct());
            firstIndexPartialDividend = i;
        }
    }

    /**
     * alignFollowingRowSpace method - align following rows by space
     */
    public void alignFollowingRowSpace(int nextPartialDividend, String dividendText, int i) {
        if (Integer.toString(nextPartialDividend).length()
                > 0 && result.getRemainder() > 0) {
            if (Integer.toString(result.getProduct()).length()
                    != Integer.toString(nextPartialDividend).length()) {
                if (i == dividendText.length()) {
                    countSpace = Integer.toString(result.getProduct()).length()
                            - Integer.toString(result.getRemainder()).length();
                } else {
                    countSpace = Integer.toString(result.getProduct()).length()
                            - Integer.toString(result.getRemainder()).length()
                            + countSpace;
                }
                System.out.println(getSpace(countSpace) + nextPartialDividend);
                countSpace++;
                System.out.println(getSpace(countSpace) + result.getProduct());
                countSpace--;
            } else if (Integer.toString(nextPartialDividend).length()
                    != Integer.toString(result.getRemainder()).length()
                    && Integer.toString(result.getRemainder()).length() > 0) {
                System.out.println(getSpace(countSpace) + nextPartialDividend);
                System.out.println(getSpace(countSpace) + result.getProduct());
                if (Integer.toString(nextPartialDividend).length()
                        == Integer.toString(nextPartialDividend - result.getProduct()).length()
                        && Integer.toString(result.getProduct()).length()
                        == Integer.toString(nextPartialDividend - result.getProduct()).length()) {
                    // Stub for save value countSpace
                } else {
                    countSpace++;
                }
            } else {
                countSpace = Integer.toString(result.getProduct()).length()
                        - Integer.toString(result.getRemainder()).length()
                        + countSpace;
                System.out.println(getSpace(countSpace) + nextPartialDividend);
                System.out.println(getSpace(countSpace) + result.getProduct());
            }
        } else if (Integer.toString(nextPartialDividend).length() > 0
                && result.getRemainder() == 0) {
            countSpace = Integer.toString(result.getProduct()).length()
                    + countSpace;
            System.out.println(getSpace(countSpace) + nextPartialDividend);
            System.out.println(getSpace(countSpace) + result.getProduct());
        }
    }

    /**
     * printLastRow method - print the last line of the application
     */
    public void printLastRow(String dividendText, int i) {
        if (i == dividendText.length() && result.getRemainder() > 0) {
            countSpace = dividendText.length() - Integer.toString(result.getRemainder()).length();
            System.out.println(getSpace(countSpace) + result.getRemainder());
        } else if (i == dividendText.length()) {
            countSpace = dividendText.length() - dividendText.substring(firstIndexPartialDividend, i).length();
            System.out.println(getSpace(countSpace) + dividendText.substring(firstIndexPartialDividend, i));
        }
    }

    /**
     * getSpace method to get the number of spaces you want
     */
    public String getSpace(int count) {
        String space = "";
        for (int i = 0; i < count; i++)
            space += " ";
        return space;
    }
}

The main task of the class is to print the result of long division

Something like this

78454|4
4    |19613
38
36
 24
 24
   5
   4
   14
   12
    2

I wrote a test

package com.*.text;


import com.*.math.Divider;
import com.*.model.Result;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class FormatterTest {
    Result result;
    Divider divider;
    Formatter formatter;
    private final ByteArrayOutputStream outputStreamCaptor = new ByteArrayOutputStream();

    @BeforeEach
    public void setUp(){
        System.setOut(new PrintStream(outputStreamCaptor));
        this.result = new Result();
        this.formatter = new Formatter(this.result);
        this.divider = new Divider(result);
        String[] testArray = new String[] {"78454", "4"};
        this.divider.divide(Integer.parseInt(testArray[0]), Integer.parseInt(testArray[1]));
    }

    @Test
    void format() {
        String expectedResult = "78454|4n4    |19613n38n36n 24n 24n   5n   4n   14n   12n    2";

        formatter.format();
        String actualResult = outputStreamCaptor.toString().trim();

        assertEquals(expectedResult, actualResult);
    }
}

My test throws an error but outputs what is displayed is what it expects

expected: <78454|4
4    |19613
38
36
 24
 24
   5
   4
   14
   12
    2> but was: <78454|4
4    |19613
38
36
 24
 24
   5
   4
   14
   12
    2>
<Click to see difference>

org.opentest4j.AssertionFailedError: expected: <78454|4
4    |19613
38
36
 24
 24
   5
   4
   14
   12
    2> but was: <78454|4
4    |19613
38
36
 24
 24
   5
   4
   14
   12
    2>
    at app//org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:55)
    at app//org.junit.jupiter.api.AssertionUtils.failNotEqual(AssertionUtils.java:62)
    at app//org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:182)
    at app//org.junit.jupiter.api.AssertEquals.assertEquals(AssertEquals.java:177)
    at app//org.junit.jupiter.api.Assertions.assertEquals(Assertions.java:1124)
    at app//com.gmail.smaglenko.division.text.FormatterTest.format(FormatterTest.java:37)
    at java.base@16.0.2/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base@16.0.2/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78)
    at java.base@16.0.2/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base@16.0.2/java.lang.reflect.Method.invoke(Method.java:567)
    at app//org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:686)
    at app//org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at app//org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at app//org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
    at app//org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
    at app//org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
    at app//org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at app//org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at app//org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at app//org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at app//org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at app//org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at app//org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at app//org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at app//org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:205)
    at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at app//org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:201)
    at app//org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:137)
    at app//org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:71)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
    at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at app//org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base@16.0.2/java.util.ArrayList.forEach(ArrayList.java:1511)
    at app//org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at app//org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base@16.0.2/java.util.ArrayList.forEach(ArrayList.java:1511)
    at app//org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at app//org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at app//org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at app//org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at app//org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at app//org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at app//org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:75)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:99)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)
    at java.base@16.0.2/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base@16.0.2/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78)
    at java.base@16.0.2/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base@16.0.2/java.lang.reflect.Method.invoke(Method.java:567)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
    at jdk.proxy1/jdk.proxy1.$Proxy2.stop(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker$3.run(TestWorker.java:193)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.executeAndMaintainThreadName(TestWorker.java:129)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:100)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:60)
    at org.gradle.process.internal.worker.child.ActionExecutionWorker.execute(ActionExecutionWorker.java:56)
    at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:133)
    at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:71)
    at app//worker.org.gradle.process.internal.worker.GradleWorkerMain.run(GradleWorkerMain.java:69)
    at app//worker.org.gradle.process.internal.worker.GradleWorkerMain.main(GradleWorkerMain.java:74)


FormatterTest > format() FAILED
    org.opentest4j.AssertionFailedError at FormatterTest.java:37

When I click I see message “contents are identical” enter image description here I can’t understand why it throws an error if contents are identical

Please share your ideas of what it could be

Is there some way to replace rn to n?

Thank you in advance!

Advertisement

Answer

I solved my problem by putting the expected result in file result.xml

78454|4
4    |19613
38
36
 24
 24
   5
   4
   14
   12
    2

And add this in my test case

String expected = new String(getClass().getClassLoader().getResourceAsStream("result.xml").readAllBytes());

Also helped to change all System.out.println to System.out.printf and

String actualResult = outputStreamCaptor.toString().trim().replaceAll("n" , "rn");
Advertisement