2

I have:

when(Long.valueOf(anyString())).thenReturn(anyLong());

It gets a NumberFormatException on Long.valueOf(String) because "" is being passed in.

The code I'm testing is this:

 final Long id = Long.valueOf(foo.bar()); 

How can I get around that?

Sled
  • 18,541
  • 27
  • 119
  • 168
mstrom
  • 1,655
  • 3
  • 26
  • 41

2 Answers2

4

This request is a bad idea.

  1. You can't use anyLong() as a return value. Mockito matchers only stand in for argument values. Mockito needs to know exactly what value to return, but you can pick an arbitrary one.

  2. You can't stub static methods using Mockito. You can only stub object instances, because Mockito needs to be able to replace the implementation with its own. You can use Powermock to stub static methods, as listed in the Powermock documentation; Powermock uses class rewriting to secretly replace the class to stub (Long here).

  3. Even if you could replace Long.valueOf easily, it wouldn't make much sense. Imagine debugging code when Long.valueOf("5") returns 7.

My recommendation is to use an object that represents what you're trying to do, then mock that.

class SystemUnderTest {
  class IdExtractor {
    long extractIdFromString(String string) {
      return Long.valueOf(string);
    }
  }

  IdExtractor idExtractor = new IdExtractor();

  public boolean reticulateSplines(String input) {
    long id = idExtractor.extractIdFromString(input);
    // ...
  }
}

@Test public void reticulateSplinesShouldWork() {
  SystemUnderTest systemUnderTest = new SystemUnderTest();
  IdExtractor mockIdExtractor = mock(SystemUnderTest.IdExtractor.class);
  systemUnderTest.idExtractor = mockIdExtractor;

  when(mockIdExtractor.extractIdFromString(anyString())).thenReturn(42L);
  assertTrue(systemUnderTest.reticulateSplines("blah"));
}
Community
  • 1
  • 1
Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251
0

I had the same issue and solved it by using org.springframework.test.util.ReflectionTestUtils, which states:

ReflectionTestUtils is a collection of reflection-based utility methods for use in unit and integration testing scenarios.

In your case, the solution might be:

ReflectionTestUtils.setField(targetObject, "foo.bar().equivalent", "stringValueHere");
jumping_monkey
  • 5,941
  • 2
  • 43
  • 58