1

I'm writing unit test (using TestNG) for a static method. When mocking the class of the static method I'm getting an exception.

@RunWith(PowerMockRunner.class)
@PrepareForTest(TempClass.class)
public class MyTestClass {

  @Test
  public void testMethodt() {
    PowerMockito.mockStatic(TempClass.class);
  }
}

public class TempClass {

  public static String getName(String name){
    return "Hi " + name;
  }
}

When execute PowerMockito.mockStatic(TempClass.class); i'm getting following exception

org.powermock.api.mockito.ClassNotPreparedException: 

[Ljava.lang.Object;@65466a6a
The class com.test.TempClass not prepared for test

Any solution for this?

Krishnan Mahadevan
  • 14,121
  • 6
  • 34
  • 66
Nibras
  • 329
  • 1
  • 6
  • 23
  • Take Care of Java naming conventions. Classnames should start with uppercase character – Jens May 24 '19 at 09:33
  • What is `com.aexistest.data.testClass`? – Jens May 24 '19 at 09:36
  • Are you using that mock? Did you configure the mock? – Amadán May 24 '19 at 09:40
  • @Jens, it's a class having static method to test. testClass edited to TempClass – Nibras May 24 '19 at 09:46
  • @Amadán, What configuration you mean? – Nibras May 24 '19 at 09:47
  • @Nibras I am not so familiar with PowerMock, but usually a mock needs to be told, how to behave when methods are called - something that might look like: doReturn(x).when(mock).foo() (Mockito) or expect(mock.foo()).andReturn(x) (EasyMock). Some frameworks provide a default implemetation, others just give you an exception that might look like your's. Mind, that after configuring your mock you also might need to set that configuration active, like in EasyMock you need to call replay(mock) after configuration. – Amadán May 24 '19 at 10:13
  • @Amadán as you mentioned i have configured the mock. but before that, i'm getting that exception – Nibras May 24 '19 at 10:41
  • Is TempClass is your mockclass?if so have u created mock for TempClass. or you can call something like this in BeforeTest .mockStatic(TempClass.class) – Porkko M May 24 '19 at 11:16
  • have a look here https://stackoverflow.com/questions/10583202/powermockito-mock-single-static-method-and-return-object – Jocke May 24 '19 at 18:30

1 Answers1

1

Fixed the issue by adding following

@PrepareForTest(TempClass.class)
public class MyTestClass extends PowerMockTestCase {
   ....
}
Nibras
  • 329
  • 1
  • 6
  • 23
  • 1
    Hint: all those things are very well documented, and they were asked here many times before. Sometimes you are much faster simply doing a bit of research, instead of putting up the 10th repetition of the same problem here ;-) – GhostCat May 28 '19 at 09:29