Guava: Non final `Stopwatch`

Created on 30 Jan 2017  路  7Comments  路  Source: google/guava

Currently Stopwatch is final which makes it impossible to mock it with mockito to unit test classes using it.
It would be great to make Stopwatch non final to avoid this problem.

Thanks!

Most helpful comment

Can you discuss why you wouldn't just use a Stopwatch created with a mocked or faked Ticker?

All 7 comments

Can you discuss why you wouldn't just use a Stopwatch created with a mocked or faked Ticker?

The excellent question of @lowasser aside, as of version 2.1.0, Mockito has incubating support for mocking final types, enums and final methods. We're successfully using this in our project.

@lowasser Thanks for your question. It is probably possible to mock Ticker for tests, but this makes tests dependent on internals of Stopwatch implementation - thing that we are trying to avoid.

@Stephan202 using newer Mockito is probably an option, but unfortunately there are situations when this is not possible or diffigult. E.g. current version of spring boot test utils requires older mockito.

It's not clear what details of Stopwatch's implementation details you're avoiding? Stopwatch's one and only job is to subtract the results of Ticker's output; there are no other implementation details.

Well, ideally in unit test we would like to make sure that our code called start/stop/etc. Not that Ticker has moved through some number of ticks.

@lowasser I ran into the same issue as @mar-kolya reports. In a unit test, I want to verify that my code called Stopwatch.elapsed, but instead had to mock Ticker and then verify its read() was called X+1 number of times (because Stopwatch calls it when it's started). Not the end of the world, but if Stopwatch interacted with ticker in other places, my test would depend on those internals.

I think you can use PowerMockito to mock the final class. Everything else you can still use Mockito to setup and verify expectation.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

cowwoc picture cowwoc  路  3Comments

Lysergid picture Lysergid  路  4Comments

JWT007 picture JWT007  路  4Comments

ernestp picture ernestp  路  3Comments

gissuebot picture gissuebot  路  3Comments