Junit 无法模拟 class
Junit cannot Mock a class
当我尝试测试一个方法并使用 PowerMock 和 Mockito 模拟其依赖性时遇到问题。我尝试将依赖方法转换为非静态方法并使用@Mock 注释和@InjectMocks 但完全没有结果。
这里是 class 和正在测试的方法:
/* class to be tested */
public class LoginServiceImpl implements LoginService{
/* method to be tested */
@Override
public String createJwt(String subject, String name, String permission, Date datenow) throws java.io.UnsupportedEncodingException{
Date expDate = datenow;
expDate.setTime(datenow.getTime()+(300*1000)); //expiration time = 30 minutes
String token = jwtUtils.generateJwt(subject, expDate, name, permission);
return token;
}
}
这里有我想要模拟的依赖项,但我在模拟时遇到了麻烦:
/* Dependency I cannot mock */
public class JwtUtils {
public static String generateJwt(String subject, Date date, String name, String scope) throws java.io.UnsupportedEncodingException{
String jwt = Jwts.builder()
.setSubject(subject)
.setExpiration(date)
.claim("name", name)
.claim("scope", scope)
.signWith(
SignatureAlgorithm.HS256,
"myPersonalSecretKey12345".getBytes("UTF-8")
)
.compact();
return jwt;
}
}
最后但并非最不重要的一点是,测试 class 的测试方法失败了。
不得不说,它甚至没有到达 assert 方法调用,而是在 when().thenResult() 处失败了。
我还必须指定我尝试使用 doReturn() 和 any() 作为匹配器,但没有结果。
@RunWith(MockitoJUnitRunner.class) //to run Mockito
@PrepareForTest({JwtUtils.class}) //powerMock annotations tomock classes containing static methods
public class LoginServiceImplTest {
@InjectMocks
LoginServiceImpl loginService; //System under test (SUT)
@Test
public void createJwtTest() throws Exception {
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
Date expdate = ft.parse("2040-12-12");
String jwt = JwtUtils.generateJwt("BDAGPP32E08F205K", expdate, "Pippo Baudo", "conduttore");
//HERE IT'S WHERE IT FAILS:
when(JwtUtils.generateJwt("BDAGPP32E08F205K", expdate, "Pippo Baudo", "conduttore")).thenReturn(jwt);
assertThat(loginService.createJwt("BDAGPP32E08F205K", "Pippo Baudo", "conduttore", expdate), is(jwt));
}
}
这是 JUnit 和 Mockito 给我的错误:
org.mockito.exceptions.misusing.MissingMethodInvocationException: when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods. Those methods cannot be stubbed/verified. Mocking methods
declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.
at
com.example.bytecode.SpringBootJWT.services.LoginServiceImplTest.createJwtTest1(LoginServiceImplTest.java:114)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498) at
org.junit.runners.model.FrameworkMethod.runReflectiveCall(FrameworkMethod.java:50)
at
org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at
org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at
org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner.run(ParentRunner.java:290) at
org.junit.runners.ParentRunner.schedule(ParentRunner.java:71) at
org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at
org.junit.runners.ParentRunner.access[=14=]0(ParentRunner.java:58) at
org.junit.runners.ParentRunner.evaluate(ParentRunner.java:268) at
org.junit.runners.ParentRunner.run(ParentRunner.java:363) at
org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at
org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at
com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at
com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at
com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at
com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Process finished with exit code 255
没有规定 utility classes 中的方法必须是 static
!
实际上这是一种不好的做法,因为它会使您的代码高度耦合且不灵活。您替换此依赖项的问题证明了这一点。
因此,与其屈服于你糟糕的设计并使用 PowerMock,你应该通过删除 static
键来应用 控制反转 方法中的单词将 class 的一个实例传递到您的单元中,最好使用 DI 框架 。
在那种情况下,您可以使用简单的 Mockito 来模拟该依赖项并且替换它没有问题。
尝试用 @RunWith(PowerMockRunner.class)
替换 @RunWith(MockitoJUnitRunner.class)
。据我所知,所有使用 PowerMock 功能的测试都必须是 运行 和 PowerMockRunner
。
当我尝试测试一个方法并使用 PowerMock 和 Mockito 模拟其依赖性时遇到问题。我尝试将依赖方法转换为非静态方法并使用@Mock 注释和@InjectMocks 但完全没有结果。
这里是 class 和正在测试的方法:
/* class to be tested */
public class LoginServiceImpl implements LoginService{
/* method to be tested */
@Override
public String createJwt(String subject, String name, String permission, Date datenow) throws java.io.UnsupportedEncodingException{
Date expDate = datenow;
expDate.setTime(datenow.getTime()+(300*1000)); //expiration time = 30 minutes
String token = jwtUtils.generateJwt(subject, expDate, name, permission);
return token;
}
}
这里有我想要模拟的依赖项,但我在模拟时遇到了麻烦:
/* Dependency I cannot mock */
public class JwtUtils {
public static String generateJwt(String subject, Date date, String name, String scope) throws java.io.UnsupportedEncodingException{
String jwt = Jwts.builder()
.setSubject(subject)
.setExpiration(date)
.claim("name", name)
.claim("scope", scope)
.signWith(
SignatureAlgorithm.HS256,
"myPersonalSecretKey12345".getBytes("UTF-8")
)
.compact();
return jwt;
}
}
最后但并非最不重要的一点是,测试 class 的测试方法失败了。 不得不说,它甚至没有到达 assert 方法调用,而是在 when().thenResult() 处失败了。 我还必须指定我尝试使用 doReturn() 和 any() 作为匹配器,但没有结果。
@RunWith(MockitoJUnitRunner.class) //to run Mockito
@PrepareForTest({JwtUtils.class}) //powerMock annotations tomock classes containing static methods
public class LoginServiceImplTest {
@InjectMocks
LoginServiceImpl loginService; //System under test (SUT)
@Test
public void createJwtTest() throws Exception {
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
Date expdate = ft.parse("2040-12-12");
String jwt = JwtUtils.generateJwt("BDAGPP32E08F205K", expdate, "Pippo Baudo", "conduttore");
//HERE IT'S WHERE IT FAILS:
when(JwtUtils.generateJwt("BDAGPP32E08F205K", expdate, "Pippo Baudo", "conduttore")).thenReturn(jwt);
assertThat(loginService.createJwt("BDAGPP32E08F205K", "Pippo Baudo", "conduttore", expdate), is(jwt));
}
}
这是 JUnit 和 Mockito 给我的错误:
org.mockito.exceptions.misusing.MissingMethodInvocationException: when() requires an argument which has to be 'a method call on a mock'. For example: when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because: 1. you stub either of: final/private/equals()/hashCode() methods. Those methods cannot be stubbed/verified. Mocking methods declared on non-public parent classes is not supported. 2. inside when() you don't call method on mock but on some other object.
at com.example.bytecode.SpringBootJWT.services.LoginServiceImplTest.createJwtTest1(LoginServiceImplTest.java:114) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.junit.runners.model.FrameworkMethod.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) at org.junit.runners.ParentRunner.run(ParentRunner.java:290) at org.junit.runners.ParentRunner.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access[=14=]0(ParentRunner.java:58) at org.junit.runners.ParentRunner.evaluate(ParentRunner.java:268) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37) at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62) at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47) at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242) at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Process finished with exit code 255
没有规定 utility classes 中的方法必须是 static
!
实际上这是一种不好的做法,因为它会使您的代码高度耦合且不灵活。您替换此依赖项的问题证明了这一点。
因此,与其屈服于你糟糕的设计并使用 PowerMock,你应该通过删除 static
键来应用 控制反转 方法中的单词将 class 的一个实例传递到您的单元中,最好使用 DI 框架 。
在那种情况下,您可以使用简单的 Mockito 来模拟该依赖项并且替换它没有问题。
尝试用 @RunWith(PowerMockRunner.class)
替换 @RunWith(MockitoJUnitRunner.class)
。据我所知,所有使用 PowerMock 功能的测试都必须是 运行 和 PowerMockRunner
。