Jmockit mock abstract class

2019-07-08 02:57发布

问题:

I have a super abstract class

public abstract class PsActionBeanContext{
    ...
    abstract public Brand getBrand();
    ..
}

I want to mock the abstract class to get default value "TESTUSER_BRAND_ID", which is a constant. I tried:

final PsActionBeanContext contextFake = new MockUp<PsActionBeanContext>(){
 @Mock
 public Brand getBrand(){
      Brand brand = new Brand();
      brand.setBrandId(TESTUSER_BRAND_ID);
      return brand;
      }
 }.getMockInstance();
}

But I got

java.lang.IllegalArgumentException: Attempted to mock abstract method "getBrand"

I tried the same way to mock an interface but that is fine.
any suggestion? thanks

回答1:

Try the following instead:

@Test
public void mockAbstractClass(@NonStrict final PsActionBeanContext mock)
{
    final Brand brand = new Brand();
    brand.setBrandId(TESTUSER_BRAND_ID);

    new Expectations() {{ mock.getBrand(); result = brand; }};

    assertSame(brand, mock.getBrand());
}