Testing abstract classes with arguments in the constructor

I am trying to learn about tests, but I have to face some problems when testing abstract classes. I know that I can create a specific subclass that inherits from Dog, for example ConcreteDog, but if I add a new abstract method for Dog, I would have to add an empty method for ConcreteDog. I think it would not be so great.

public abstract class Dog {
  private final int id;

  public Dog(int id) {
    this.id = id;
  }

  public int getId() {
    return id;
  }

  public abstract void makeSound();
}

...

public class DogTest {
  @Test
  public void testGetId() {
    int id = 42;

    // How to pass id to Dog constructor ?
    Dog dog = Mockito.mock(Dog.class, Mockito.CALL_REAL_METHODS);

    assertTrue(dog.getId() == id);
  }
}

What I'm trying to do is somehow call Mock with a constructor, like

Mockito.mock(Dog(id).class, Mockito.CALL_REAL_METHODS);

I don't know if this is possible with mockito, but is there a way to do this with mockito or another tool?

+4
source share
2 answers

, , , .

Dog dog = Mockito.mock(Dog.class, Mockito.CALL_REAL_METHODS);
ReflectionTestUtils.setField(dog , "id", 42);
+2

Dog , .

class TestDog extends Dog {
...
}

TestDog ​​ . , TestDog.class, TestDog, ...

TestDog mock_dog = mock(TestDog.class); 
when(mock_dog.getId()).thenReturn(99);
whenNew(TestDog.class).withArguments(anyInt()).thenReturn(mock_dog);

0

Source: https://habr.com/ru/post/1657004/


All Articles