使用ArgumentsMatchers和Mockito来模拟一个类类型的参数 – Mongo聚合Spring Webflux

huangapple go评论68阅读模式
英文:

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>any())))
.thenReturn(Flux.just(fooData));

英文:

I have this call to MongoDB and I want to mock it.

private ReactiveMongoTemplate reactiveMongoTemplate;

...constructor

reactiveMongoTemplate.aggregate(aggregation, &quot;foo_collection&quot;, 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.&lt;Class&lt;FooData&gt;&gt;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));

huangapple
  • 本文由 发表于 2020年9月8日 08:09:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/63785580.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定