java – What is the right way to test in unit tests?

Question:

Suppose there are several classes A, B and C. We are testing A. The rest of the classes are mocks. Class A has a method, inside which it uses B and C and outputs the result.

Do I need to test that class A interacts with B and C, or write one test in which the result of executing method A will be checked?

Whether to do such a test in the following case:

class A implements B.OnBarCallback {
  private B b;

  public A(B b) {
    this.b = b;
  }

  public void foo() {
    b.bar(this);
  }

  @Override
  public void onBar() {
    // do something
  }
}

// тест вызова B
void testCallB() {
  B mockB = mock(B.class);
  A a = new A(mockB);
  a.foo();
  verify(mockB).bar(any(OnBarCallback.class));
}

// тест callback
void testACallback() {
  B mockB = mock(B.class);
  A a = new A(mockB);
  a.onBar();
  // do verify something
}

Is it correct to manually pull the callback method in a dough?

Answer:

If we go completely by the rules, then the unit test should test the minimum unit of code. I have such an internal rule – if I suddenly needed to debug the execution of a unit test, because I don’t understand how it works, it means that this is not a unit test, it is testing too large a piece of code.

Therefore, if classes B and C are large enough and not trivial (for example, they read files from disk, download from the Internet), then it is better to lock them up and test with mocks in class A. And if B / C methods add two numbers, then I see no particular reason to mock them.

Is it necessary to test that class A interacts with B and C

But nobody cancels class interaction tests together. It's just called integration tests. And they are also needed and useful.

or write one test in which the result of executing method A will be checked?

But how many tests to write is already a philosophical question. But one is usually not enough.

Scroll to Top