java - Junit 不能模拟一个类

标签 java unit-testing junit mocking stub

当我尝试测试一个方法并使用 PowerMock 和 Mockito 模拟其依赖性时遇到问题。我尝试将依赖方法转换为非静态方法并使用 @Mock 注释和 @InjectMocks 但没有任何结果。

下面是被测类和方法:

/* 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;
   }
}

最后但并非最不重要的是,测试类的测试方法失败了。 不得不说,它甚至没有到达 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$1.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$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.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

最佳答案

尝试将 @RunWith(MockitoJUnitRunner.class) 替换为 @RunWith(PowerMockRunner.class)。据我所知,所有使用 PowerMock 功能的测试都必须使用 PowerMockRunner 运行。

关于java - Junit 不能模拟一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46091335/

相关文章:

java - 在给定范围内用Java生成随机小写字母

c# - MSTest 测试上下文异常处理

java - 为什么要使用模拟对象 (Java)?所有模拟框架都服务于相同的目的吗?

unit-testing - 你如何从 Rhino.Commons 模拟 UnitOfWork?

java - 未找到 Wicket 单元测试 Translations.utils

java - 如何在 JUnit 5 中使用 @RestTemplateClient?

java - 使用 MockMVC 在 JUnitTest 中注册 @ControllerAdvice 带注释的 Controller

Java将两个不同大小的List合并为HashMap

java - 为什么 Date 对象返回错误的日期?

java - Maven 模块 - 如何在不相关的项目中将其用作外部库