jUnit-Testing from another class - java

I simplified the problem.
I have 3 classes:
My operating class, which has just one static method (add) in it, which should add to ints:
public class T{
public static int add(int a, int b){
return a+b;
}
}
I am pretty sure, there is no error in this simple method. Here is my jUnit-Test:
import org.junit.*;
import static org.junit.Assert.*;
import junit.framework.TestCase;
public class MyJUnitTest extends TestCase{
T t;
public boolean test(){
junit.framework.TestResult t = this.run();
System.out.println(t.wasSuccessful());
System.out.println(t.failures.nextElement());
return t.wasSuccessful();
}
public void setUp() throws Exception {
t = new T();
}
public void tearDown() throws Exception {
t = null;
}
//#Test
public void test1(){
int[] vgl1 = new int[1];
int[] vgl2 = new int[1];
vgl1[0] = t.add(1,2);
vgl2[0] = 3;
Assert.assertArrayEquals("Test one", vgl1, vgl2);
}
}
Note: I test with Arrays, because in my not simplified Version of the problem, there are Arrays, which I have to test.
Here comes the problem, I cannot understand: If I run the Test in my IDE I get a success (till here, quite understandable), but if I run a third class with one static method:
public class A{
public static void abc(){
MyJUnitTest t = new MyJUnitTest();
t.test();
}
}
I get a failureCount of one and wasSuccessful returns false. Also System.out.println(t.failures.nextElement()); prints null(MyJUnitTest): TestCase.fName cannot be null.
This is, what I cannot understand. The test should be successful!
Also I tried to use jUnit4, which means, I adapted my MyJUnitTest-Class. But doing so, I cannot call the run-Method. Is there an equivalent in jUnit4? In my IDE I can just click on "test All", but I need to make the Tests in another class an get the information, wheather all Test were successful.

Related

Junit error in Eclipse

package com.test;
public class Calculation {
public static int add(int n1, int n2)
{
return n1 + n2;
}
public static int sub(int n1, int n2)
{
return n1 * n2;
}
}
Above is my class and
below is my JUnit test class
package com.test;
import static org.junit.Assert.*;
import org.junit.Test;
public class CalculationTest extends Calculation
{
CalculationTest test = new CalculationTest();
#Test
public void testadd()
{
assertEquals(9,Calculation.add(1,8));
}
public void testsub()
{
assertEquals(12,Calculation.sub(15,3));
}
}
Hello any help would be appreciated i'm currently trying to get an error on my subtest because it's wrong in my class, however the error i'm currently getting is on Line 9 of my junit which is why I can't figure why it's causing an error.
CalculationTest test = new CalculationTest();
Your sub method has an error:
public static int sub(int n1, int n2) {
return n1 - n2;
}
Secondly I would advise you to dispose of static methods. Non static methods are better when testing, overwriting. So if you have a chance to make them non-static I would encourage you do change them.
So your test sould look like thos:
public class CalculationTest {
#Test
public void testAdd()
{
assertEquals(9,Calculation.add(1,8));
}
#Test
public void testSub()
{
assertEquals(12,Calculation.sub(15,3));
}
}
Line 9, CalculationTest test = new CalculationTest();, causes the default constructor to be called on creation of a new CalculationTest instance. The code declares that a CalculationTest instance contains a CalculationTest instance. This is likely to recurse infinitely, and in fact does do so on my computer, resulting in the JVM throwing a StackOverflowError.
The test member of CalculationTest is not used and does not appear to be needed - perhaps consider simply removing that line then addressing the other issues raised in other answers and comments of this question?

PowerMockito whenNew doesn't work with multiple constructors

whenNew is not working if I have two constructors - one without and one with arguments. In the code excerpt below I need the real constructor to be called a second time, but I get a NullPointerException instead.
#RunWith(PowerMockRunner.class)
public class UtilTest {
#Test
public void test()throws Exception {
A a= new A();
a.setI(10);
whenNew(A.class).withNoArguments().thenReturn(a);
UtilTest test= new UtilTest();
test.testA();
}
private void testA(){
A a1= new A();
System.out.println(a1.getI());
A a2= new A(50);
System.out.println(a2.getI());
}
}
class A{
int i=1;
public A(){}
public A(int i){
this.i=i;
}
public void setI(int i){
this.i=i;
}
public int getI(){
return this.i;
}
}
Output -
10
java.lang.NullPointerException
(1) Keep class newInstance(int) method before class manipulations
(2) Try to define both constructors.
whenNew(A.class)
.withNoArguments()
.thenReturn(a);
whenNew(A.class)
.withArguments(...)
.doAnswer(call original constructor);

How to replace method invocation with mock?

I have a class with two methods. I want to replace invocation of second method with expected result.
Here is my class under test
public class A {
public int methodOne() {
return methodTwo(1);
}
public int methodTwo(int param) {
// corresponding logic replaced for demo
throw new RuntimeException("Wrong invocation!");
}
}
And test
public class ATest {
#Test
public void test() {
final A a = spy(new A());
when(a.methodTwo(anyInt())).thenReturn(10);
a.methodOne();
verify(a, times(1)).methodTwo(anyInt());
}
}
Why I'm get an exception when start the test?
Two things that will help you here. First, from the documentation it seems you need to use the do*() api with spy() objects. Second, to call the "real" method you need to declare it specifically using doCallRealMethod()
Here's the updated test that should work for you:
public class ATest {
#Test
public void test() {
final A a = spy(new A());
doReturn(10).when(a).methodTwo(anyInt());
doCallRealMethod().when(a).methodOne();
a.methodOne();
verify(a, times(1)).methodTwo(anyInt());
}
}

In testing in java how to check if a method of an interface is called or not?

I want to test this class which calls a method of interface using anonymous class.
public class ClassToTest
{
public void methodToTest()
{
InterefaceToMock interefaceToMockReference = new InterefaceToMock() {
#Override
public int methodToMock()
{
return 0;
}
};
interefaceToMockReference.methodToMock();
}
}
This is the interface
public interface InterefaceToMock
{
public int methodToMock();
}
I am using this approch to check it methodToMock is called or not
import static org.junit.Assert.*;
import org.junit.Test;
import mockit.FullVerificationsInOrder;
import mockit.Mocked;
import mockit.NonStrictExpectations;
public class TestAClass
{
#Mocked InterefaceToMock interefaceToMockReferenceMocked;
#Test
public void test1()
{
new NonStrictExpectations()
{
{
interefaceToMockReferenceMocked.methodToMock();times=1;
}
};
(new ClassToTest()).methodToTest();
new FullVerificationsInOrder(interefaceToMockReferenceMocked)
{
};
assertTrue(true);
}
}
But test case fails.
Can anyone help.
Your original test was almost correct. It declared the mock field as simply being #Mocked, which merely gives you a single mocked instance implementing the interface, and this is not the one used by the code under test. The JMockit API has another mocking annotation, however, which extends mocking to all implementation classes from a given base type, and by default affects all instances of said classes. So, the test should be changed as follows:
public class TestAClass
{
#Capturing InterfaceToMock anyImplementingInstance;
#Test
public void test1()
{
new ClassToTest().methodToTest();
new Verifications() {{
anyImplementingInstance.methodToMock();
}};
}
}
In the general case, if you have an class and you want to check whether a method on a Mock of that class is called, you use Mockito.verify.
For example:
public class AppTest {
#Test
public void testMe() {
final ITest iTest = Mockito.mock(ITest.class);
final CUT cut = new CUT(iTest);
cut.doStuff();
Mockito.verify(iTest).someStuff();
}
interface ITest {
void someStuff();
}
class CUT {
private final ITest iTest;
CUT(ITest iTest) {
this.iTest = iTest;
}
public void doStuff() {
iTest.someStuff();
}
}
}
Here, the test is whether ITest.someStuff() is called from CUT.doStuff().
Your example is undecipherable...

Proper usage of Mockito.verify

I'm new to unit testing and i had a simple question regarding the usage of verify method used in Mockito. here's the class i used for testing.
public class Foo{
int n = 0;
void addFoo(String a){
if(a == "a")
add(1);
}
protected void add(int num){
n =1;
}
public int get(){
return n;
}
}
And here's my Unit test.
public class FooTest {
#Mock Foo f;
#Test
public void test() {
MockitoAnnotations.initMocks(this);
f.addFoo("a");
//Passes
Mockito.verify(f).addFoo("a");
//Fails
Mockito.verify(f).add(1);
}
}
And i get a
Wanted but not invoked:
f.add(1);
-> at FooTest.test(FooTest.java:22)
However, there were other interactions with this mock:
-> at FooTest.test(FooTest.java:16)
exception.
How do you verify that add(int num) is called ?
I think you misunderstood the point of verify.
In your test, Foo f is a mock object - Foo's internal implementation is ignored, and only the behavior you recorded on it (using when(f.someMethod().thenXXX) would happen.
The point of mocking and verifying is to test interactions while ignoring the internal implementation.
In this example, you would probably have another class that uses Foo, and you'd want to test whether it invokes the correct methods of the given Foo instance.
Quick example:
Assume you have a class the uses the Foo class you presented in your question:
public class FooUser {
private Foo f;
public void setFoo(Foo f) {
this.f = f;
}
public Foo getFoo() {
return f;
}
public void addToFoo(String string) {
f.add(string);
}
}
Now, you'd want to test that FooUser#addToFoo(String) indeed invokes the correct add(String) method of Foo:
#RunWith (MockitoJUnitRunner.class)
public class FooUserTest {
#Mock Foo f;
FooUser fUser;
#Before
public void init() {
fUser = new FooUser();
fUser.setFoo(f);
}
#Test
public void test() {
fUser.addToFoo("a");
Mockito.verify(f).addFoo("a");
}

Categories