Simon Guo
Simon Guo

Reputation: 2926

Junit Test Empty Method

I have a class called NullMetricsPublisher, there are a few methods inside, for example one of them void publish(). As the class name already indicates that the class should doing nothing. The void publish() method is essentially empty.

void publish() {
    // do nothing in this method
}

However, we do want to unit test it, make sure no logic inside the method at all. Wondering anyone know how to test an empty method of a class in Java?

Note: Why we have NullMetricsPublisher in first place? We do have another class called MetricsPublisher, which publishes metrics to our metrics service. However, in some cases, we don't want to publish metrics to at all. The existing interface must require a Publisher, therefore, now we just added NullMetricsPublisher class to implement Publisher.

Upvotes: 7

Views: 8576

Answers (2)

Celos
Celos

Reputation: 517

When using dependency injection, you could verify that:

  1. No internal state is changed.
  2. No dependencies are called.

This would effectively make whatever the method does a no-op. There are multiple ways to verify point 1: manually check the state, serialize the object before and after etc. Point 2 can simply be solved by passing in dependencies that throw on any invocation.

This solution does break down if you have some static global classes, like Environment.getConnection().publish() or aren't using DI.

Upvotes: 0

Stefan Birkner
Stefan Birkner

Reputation: 24520

You cannot test that a method does nothing with a unit test. In order to test this you would need to check that nothing that could happen, does happen. There are endless things that could happen. Therefore it is not possible to write a unit test for this.

The only thing you could test is that specific actions don't happen, e.g. the NullMetricsPublisher doesn't send messages like the MetricsPublisher.

Upvotes: 5

Related Questions