【问题标题】:Spring boot test - PowerMockito to mock and stub constructorSpring Boot 测试 - PowerMockito 模拟和存根构造函数
【发布时间】:2017-05-01 22:15:15
【问题描述】:

使用 Spring Boot 启动器测试来测试我的应用程序,但我使用的是第三方库。假设我们有一个 TRequest 类,它有一些构造函数,我想模拟和存根该构造函数以返回结果。

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

@MockBean
TRequest trequest ; 

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

}
}

现在,当我尝试使用 new 创建构造函数时,它没有返回正确的存根结果。

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

【问题讨论】:

  • 可能需要在您的测试中使用PowerMockitoRunner,然后才能拦截该构造。如果你想用 spring 运行它,也可以看看@PowerMockRunnerDelegate

标签: spring unit-testing junit spring-boot powermock


【解决方案1】:

已使用jackson 第三方库进行测试。 - 由于 PowerMock 导致 ClassLoader 异常。

@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());
    }

}

【讨论】:

  • 但现在@Autowired 无法在此工作。无法获取依赖的错误来了。
  • 仍然必须用 @SpringBootTest 注释类 - 但是当我这样做时,我会从 powermock 获得 LinkageExceptions。我现在似乎找不到解决方案。
  • 是的,我遇到了同样的错误。请关注此网址github.com/spring-projects/spring-boot/issues/6808。似乎 powermockito 已经在他们最新的 1.6.6 版本中解决了这个问题,但我无法看到如何去做。
  • 收到这些错误时,我正在使用 powermock 1.6.6 和 spring-boot 1.4.0,所以显然没有解决。
猜你喜欢
  • 1970-01-01
  • 2011-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多