Jira的二次开发,需要作单元测试。
测试跟数据库连接的类,比如service类,需要在类上加@RunWith(ActiveObjectsJUnitRunner.class).
有时需要搭配mockito使用,jira里好像是内置了mockito还是怎么回事,不用再类上加@RunWith(MockitoJUnitRunner.class),也可以模拟类
但是当有需要模拟类的静态方法和私有方法时,mockito就使不上力了,这是需要导入PowerMock。但是@RunWith只能接收一个参数,而且也不能再类上使用两个@RunWith。
查阅资料,找到一个博客
Using another JUnit Runner with PowerMock
里面有降到如何在使用PowerMockRunner,可以接着使用其他Runner,样例里是SpringJUnit4ClassRunner
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 package org.powermock.examples.spring.mockito; 2 3 import org.junit.Test; 4 import org.junit.runner.RunWith; 5 import org.powermock.core.classloader.annotations.PowerMockIgnore; 6 import org.powermock.core.classloader.annotations.PrepareForTest; 7 import org.powermock.modules.junit4.PowerMockRunner; 8 import org.powermock.modules.junit4.PowerMockRunnerDelegate; 9 import org.springframework.beans.factory.annotation.Autowired; 10 import org.springframework.test.context.ContextConfiguration; 11 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 12 import powermock.examples.spring.IdGenerator; 13 import powermock.examples.spring.Message; 14 import powermock.examples.spring.MyBean; 15 16 import static org.junit.Assert.assertEquals; 17 import static org.powermock.api.mockito.PowerMockito.*; 18 import static org.powermock.api.support.membermodification.MemberMatcher.method; 19 import static org.powermock.api.support.membermodification.MemberModifier.stub; 20 import static org.powermock.api.support.membermodification.MemberModifier.suppress; 21 22 @RunWith(PowerMockRunner.class) 23 @PowerMockRunnerDelegate(SpringJUnit4ClassRunner.class) 24 @ContextConfiguration("classpath:/example-context.xml") 25 @PrepareForTest(IdGenerator.class) 26 public class SpringExampleTest { 27 28 @Autowired 29 private MyBean myBean; 30 31 @Test 32 public void mockStaticMethod() throws Exception { 33 // Given 34 final long expectedId = 2L; 35 mockStatic(IdGenerator.class); 36 when(IdGenerator.generateNewId()).thenReturn(expectedId); 37 38 // When 39 final Message message = myBean.generateMessage(); 40 41 // Then 42 assertEquals(expectedId, message.getId()); 43 assertEquals("My bean message", message.getContent()); 44 } 45 }
但是,自己在使用时,并未生效
1 PowerMockito.doAnswer(e -> { 2 String key = (String) e.getArguments()[0]; 3 。。。 4 } 5 }).when(exportEmployeeCSV, "getSex", anyString());
目的是模拟私有方法,并且不执行私有方法内部的代码,但是多次调整代码还是会执行内部代码。
继续看评论,好像是版本问题
修改为最新版本,重新运行测试用例,Green Bar!