EasyMock - mock object returned from a new object

Is it possible, for example, to capture to return the layout when calling a method from a new object?

To make it more specific:

SecurityInterface client = new SecurityInterface(); port = client.getSecurityPortType(); --> I want to mock this. 

easymock version: 3.3.1

+2
source share
2 answers

Yes, if you also use Powermock , your test code can intercept calls to new and return the layout instead. This way you can return the layout for new SecurityInterface() and then mock its recipient

Powermock is compatible with Easymock

 @RunWith(PowerMockRunner.class) @PrepareForTest( MyClass.class ) public class TestMyClass { @Test public void foo() throws Exception { SecurityInterface mock = createMock(SecurityInterface.class); //intercepts call to new SecurityInterface and returns a mock instead expectNew(SecurityInterface.class).andReturn(mock); ... replay(mock, SecurityInterface.class); ... verify(mock, SecurityInterface.class); } } 
+2
source

No - this is exactly the static connection that you must develop from your classes to make them verifiable.

You will need to provide SecurityInterface through the provider or factory that you enter: then you can enter an instance that calls new in your production code, and an instance that returns the layout in your test code.

 class MyClass { void doSomething(SecurityInterfaceSupplier supplier) { Object port = supplier.get().getSecurityPortType(); } } interface SecurityInterfaceSupplier { SecurityInterface get(); } class ProductionSecurityInterfaceSupplier implements SecurityInterfaceSupplier { @Override public SecurityInterface get() { return new SecurityInterface(); } } class TestingSecurityInterfaceSupplier implements SecurityInterfaceSupplier { @Override public SecurityInterface get() { return mockSecurityInterface; } } 
+1
source

Source: https://habr.com/ru/post/1235151/


All Articles