英文:
Mock a class type argument with ArgumentsMatchers and Mockito - Mongo aggregation Spring Webflux
问题
我有这个对MongoDB的调用,我想对它进行模拟。
private ReactiveMongoTemplate reactiveMongoTemplate;
...构造函数
reactiveMongoTemplate.aggregate(aggregation, "foo_collection", FooData.class);
我尝试了以下代码,但总是得到一个```NullPointerException```错误:
Mockito.when(reactiveMongoTemplate.aggregate(ArgumentMatchers.any(), ArgumentMatchers.anyString(), ArgumentMatchers.any()))
.thenReturn(Flux.just(fooData));
我还尝试了以下代码,但得到相同的错误:
Mockito.when(reactiveMongoTemplate.aggregate(ArgumentMatchers.any(), ArgumentMatchers.anyString(), ArgumentMatchers.<Class
.thenReturn(Flux.just(fooData));
英文:
I have this call to MongoDB and I want to mock it.
private ReactiveMongoTemplate reactiveMongoTemplate;
...constructor
reactiveMongoTemplate.aggregate(aggregation, "foo_collection", FooData.class);
I tried with this but get a NullPointerException
, always
Mockito.when(reactiveMongoTemplate.aggregate(ArgumentMatchers.any(), ArgumentMatchers.anyString(), ArgumentMatchers.any()))
.thenReturn(Flux.just(fooData));
I'm also tried with this and get the same error
Mockito.when(reactiveMongoTemplate.aggregate(ArgumentMatchers.any(), ArgumentMatchers.anyString(), ArgumentMatchers.<Class<FooData>>any())))
.thenReturn(Flux.just(fooData));
答案1
得分: 0
代码部分不要翻译,只返回翻译好的内容:
模拟似乎是正确的,你在测试类中初始化了 Mockito
吗?
public class TestClass {
@Before
public void initTest() {
MockitoAnnotations.initMocks(this);
}
//..
}
或者:
@RunWith(MockitoJUnitRunner.class)
public class TestClass {
//...
}
在类测试中,你是否使用 @Mock
来注入 ReactiveMongoTemplate
?
public class TestClass {
@Mock
private ReactiveMongoTemplate reactiveMongoTemplate;
//..
}
英文:
The mock seems to be correct, have you initialized Mockito
in the test class?
public class TestClass {
@Before
public void initTest() {
MockitoAnnotations.initMocks(this);
}
//..
}
Or:
@RunWith(MockitoJUnitRunner.class)
public class TestClass {
//...
}
Are you using @Mock
to inject ReactiveMongoTemplate
in the class test?
public class TestClass {
@Mock
private ReactiveMongoTemplate reactiveMongoTemplate;
//..
}
答案2
得分: 0
我发现可以使用模拟解决方法,代码如下:
Mockito.when(reactiveMongoTemplate.aggregate(any(Aggregation.class), anyString(), eq(FooData.class)))
.thenReturn(Flux.just(fooData));
英文:
I found the solution using the mock like this:
Mockito.when(reactiveMongoTemplate.aggregate(any(Aggregation.class), anyString(), eq(FooData.class)))
.thenReturn(Flux.just(fooData));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论