PowerMockRunner和ActiveObjectsJUnitRunner

Jira的二次开发,需要作单元测试。

测试跟数据库连接的类,比如service类,需要在类上加@RunWith(ActiveObjectsJUnitRunner.class).

有时需要搭配mockito使用,jira里好像是内置了mockito还是怎么回事,不用再类上加@RunWith(MockitoJUnitRunner.class),也可以模拟类

但是当有需要模拟类的静态方法和私有方法时,mockito就使不上力了,这是需要导入PowerMock。但是@RunWith只能接收一个参数,而且也不能再类上使用两个@RunWith。

查阅资料,找到一个博客

Using another JUnit Runner with PowerMock

里面有降到如何在使用PowerMockRunner,可以接着使用其他Runner,样例里是SpringJUnit4ClassRunner

 package org.powermock.examples.spring.mockito;

 import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import powermock.examples.spring.IdGenerator;
import powermock.examples.spring.Message;
import powermock.examples.spring.MyBean; import static org.junit.Assert.assertEquals;
import static org.powermock.api.mockito.PowerMockito.*;
import static org.powermock.api.support.membermodification.MemberMatcher.method;
import static org.powermock.api.support.membermodification.MemberModifier.stub;
import static org.powermock.api.support.membermodification.MemberModifier.suppress; @RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:/example-context.xml")
@PrepareForTest(IdGenerator.class)
public class SpringExampleTest { @Autowired
private MyBean myBean; @Test
public void mockStaticMethod() throws Exception {
// Given
final long expectedId = 2L;
mockStatic(IdGenerator.class);
when(IdGenerator.generateNewId()).thenReturn(expectedId); // When
final Message message = myBean.generateMessage(); // Then
assertEquals(expectedId, message.getId());
assertEquals("My bean message", message.getContent());
}
}

但是,自己在使用时,并未生效

 PowerMockito.doAnswer(e -> {
String key = (String) e.getArguments()[0];
。。。
}
}).when(exportEmployeeCSV, "getSex", anyString());

目的是模拟私有方法,并且不执行私有方法内部的代码,但是多次调整代码还是会执行内部代码。

继续看评论,好像是版本问题

PowerMockRunner和ActiveObjectsJUnitRunner

修改为最新版本,重新运行测试用例,Green Bar!

上一篇:spring 线程安全


下一篇:poj3155 最大密度子图