简体   繁体   中英

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 .

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, eg the NullMetricsPublisher doesn't send messages like the MetricsPublisher .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM