Closed russelyang closed 10 years ago
Please note the API documentation for MockUp#getInstance() says it always returns null when the mocked type is a class.
But how can I get an object of the class? ServletOutputStream is an abstract class, I have no way to grab an object instance? Did I miss something?
I am really need MockUp
For concrete class , it is kind of make sense, but Abstract class should be treated the same way as Interface. updated sample
public class Playgroud {
abstract class A {
private void doNothing() {}
public void doSomething(int i) {}
}
@Test
public void doSomething() {
A a = new MockUp<A>() {
@Mock void doNothing() {}
}.getMockInstance();
assertNotNull(a);
}
}
Yes, MockUp doesn't have the ability to generate a subclass for an abstract class. The @Mocked/Expectations API does, though. You can obtain an abstract class instance by declaring a mock field or mock parameter of the abstract class type.
Although @mocked Expectations can generate mock instance, like ServletOutputStream case, what I need is a state testing, I want to check what write in the servletOutputStream is correct. Thank you for you time reply the question, I create a FakeServerOutputStream extend ServletOutputStream work around this case.
import mockit.Mock; import mockit.MockUp; import mockit.Mocked; import org.junit.Test;
import javax.servlet.ServletOutputStream;
import static org.junit.Assert.assertNotNull;
/**
Created by ruyang on 7/23/2014. */ public class Playgroud {
class A { private void doNothing() {} public void doSomething(int i) {} }
@Test public void mockServletOutputStream() { ServletOutputStream stream = new MockUp() {
@Mock
public void $clinit() { /* do nothing */ }
@Mock
public void $init() {}
}
@Test public void doSomething() { A a = new MockUp() { @Mock void doNothing() {} }.getMockInstance(); assertNotNull(a); } }
my assertions are failing, checked 1.9 source code, it seems caused by private T redefineClassOrImplementInterface(@NotNull Class classToMock, @Nullable Type typeToMock)
{
if (classToMock.isInterface()) {
return new MockedImplementationClass(this).generate(classToMock, typeToMock);
}
}
it should return mocked object, not null.