Home > Enterprise >  when testing a class, check the work inside the method using a Junit and a Mockito
when testing a class, check the work inside the method using a Junit and a Mockito

Time:12-10

I have a class that I cover with tests, I am having difficulties, how can I check that inside a method addBeginList(), the operation "list.add (int)" occurs on a specific list. Using the Moсkito library, check that a specific method was called on a list in a class?

public class ClassA implements IClassA {

private List<Integer> list;

public ClassA (List<Integer> list) {
    this.list = list;
}

@Override
public int addBeginList() {

    long t1 = System.currentTimeMillis();
    list.add(5);
    long t2 = System.currentTimeMillis();

    return (int) t2 - (int) t1;
}

Test class

@RunWith(MockitoJUnitRunner.class)
public class ClassATest{

private ClassA mockClassA;
private static final int EXPECTED = 0;
private static final int DELTA = 1000;
private static final int SIZE = 7000;


@Before
public void setUp() throws Exception {
    mockClassA = Mockito.mock(ClassA.class);
    mockClassA.initialize(SIZE);
    mockClassA.addBeginList();
}

@Test
public void initialize() {
   
}

@Test
public void addBeginList() {
    assertEquals(EXPECTED, mockClassA.addBeginList(), DELTA);
}

CodePudding user response:

First step is to make sure to test the real instance of the ClassA, not a mock.

Next you can either supply to it a real list and check that it contains a certain element after, or you supply it with a mocked list and check with Mockito that specific method was called:

verify(mockedList).add(5)

CodePudding user response:

I found a solution to my problem:

public class ClassA extends AbstractList<Integer> implements IClassA {///}

In test class:

private List<Integer> mockedList;
private ClassA classA;

@Before
public void setUp() throws Exception {
    mockedList = Mockito.mock(ClassA.class);
    classA = new ClassA(mockedList);
}

@Test
public void addBeginList() {
    assertEquals(EXPECTED, classA.addBeginList(), DELTA);
    verify(mockedList).add(5);
}
  • Related