junit - How to mock a method which takes Class as parameter -
i can mock method printmyvalue(string value); when(myclass.printmyvalue(anystring())then return "some value";
but how can mock printmyvalue(myclass value);
you can use "any" method. can't statically import it. code this:
package jtsandbox; import static org.hamcrest.corematchers.is; import static org.hamcrest.matcherassert.assertthat; import static org.mockito.mockito.mock; import static org.mockito.mockito.when; import org.junit.test; import org.mockito.mockito; /** * explains mocking question http://stackoverflow.com/questions/29392623/how-to-mock-a-method-which-takes-class-as-parameter/29393040#29393040 * @author jason w. thompson (https://plus.google.com/+jasonwthompson_softwaredeveloper) */ public class teststuff { /** * tests mocking * @throws exception exception not expected thrown */ @test public void testmethod() throws exception { // given final foo mockfoo = mock(foo.class); when(mockfoo.printmyvalue(mockito.<class<?>>any())).thenreturn("hi!"); // when final string answer = mockfoo.printmyvalue(string.class); // assertthat(answer, is("hi!")); } public interface foo { public string printmyvalue(class<?> clazz); } }
Comments
Post a Comment