j9d*_*9dy 8 java unit-testing mockito
我正在尝试为我的Javalin.io Web 应用程序编写单元测试。有一些对 Mockito 的引用用于模拟Context 对象,这是 Javalins 为用户提供对传入 Web 请求的访问权限的方式。我试图模拟该类的.header(String)方法,Context因为被测单元正在读取“授权”标头并对其执行 JWT 检查。
我的 pom 包含最新版本的 Mockito,它应该能够模拟最终类:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>3.2.0</version>
<scope>test</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)
我通过创建resources/mockito-extensions/org.mockito.plugins.MockMaker包含内容的文件,启用了 Mockito 文档中所述的内联模拟生成器mock-maker-inline。
现在我有一个愚蠢的测试,它Context模拟一个对象,并且每当调用上下文对象的 header() 方法时都应该返回“hello123”。以下代码是真实单元测试的一部分,但足以在运行测试时引发异常:
@Test
void stupidTest1() {
Context context = mock(Context.class);
String test1 = "hello123";
when(context.header("Authorization")).thenReturn(test1);
}
Run Code Online (Sandbox Code Playgroud)
也试过这个:
@Test
void stupidTest1() {
Context context = mock(Context.class);
String test1 = "hello123";
given(context.header("Authorization")).willReturn(test1);
}
Run Code Online (Sandbox Code Playgroud)
执行此测试mvn test失败,但有异常:
org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
String cannot be returned by header()
header() should return Validator
***
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. This exception *might* occur in wrongly written multi-threaded tests.
Please refer to Mockito FAQ on limitations of concurrency testing.
2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies -
- with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.
at my.package.stupidTest1(JavalinTest.java:28)
Run Code Online (Sandbox Code Playgroud)
有什么我做错了吗?奇怪的一点是,测试有时会成功运行,但大部分时间都会失败,尤其是在连续运行mvn test几次命令时。
我可以在本地重现该问题。类加载过程中似乎出现问题,Mockito每次都找不到正确的方法。您可以按如下方式更改测试,以确保它找到正确的标头方法。它在我当地有效。
@Test
public void stupidTest1() {
Context context = mock(Context.class);
String test1 = "hello123";
Validator<String> f = new Validator<String>("hello123","Value");
when(context.header(test1,String.class)).thenReturn(f);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
429 次 |
| 最近记录: |