简体   繁体   中英

Spring boot test - PowerMockito to mock and stub constructor

Using Spring boot starter test for testing my application but I am using third party library. Lets suppose we have a class TRequest and it has some constructor and I want to mock and stub that constructor to return the result.

@SpringBootTest
@RunWith(SpringRunner.class)
@PrepareForEverythingForTest
public class TestClass {

@MockBean
TRequest trequest ; 

@Before
public void setUp() throws Exception {
    PowerMockito.whenNew(TRequest.class).withAnyArguments().thenReturn(trequest);

}
}

Now when I am trying to create the constructor using new, it is not returning the correct stubbed result.

  TRequest trequest1 = new TRequest("apiKey","secretKey") ; 
  trequest.equals(trequest1) ; // false but I want it to be true

Have used a jackson third party lib to test with. - getting ClassLoader exceptions because of PowerMock though.

@SpringBootTest
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringRunner.class)
public class TestPowerMockito {

    @MockBean
    ObjectMapper object;

    @Before
    public void init() throws Exception {
        PowerMockito.whenNew(ObjectMapper.class).withAnyArguments().thenReturn(object);
    }

    @Test
    public void test() {
        assertEquals(object, new ObjectMapper());
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM