【问题标题】:how to mock a mehod using spring boot SpringJUnit4ClassRunner where mongo tamplate is used where the method contains static call如何使用spring boot SpringJUnit4ClassRunner模拟方法,其中使用mongotemplate,方法包含静态调用
【发布时间】:2020-08-28 08:06:40
【问题描述】:

我正在共享一个包含静态方法调用的方法代码。

public List<String> getTestContent() {
        
        DistinctIterable<String> distinctIterable = mongoTemplate.getCollection("test-doc").distinct("testcontent",String.class);
         return StreamSupport.stream(distinctIterable.spliterator(),false).collect(Collectors.toList());
                 
    }

我需要模拟我共享的这个方法。我尝试了很多方法,但得到了空指针

【问题讨论】:

  • 您尝试了什么,您的测试/模拟设置是什么?您要模拟的静态调用在哪里,方法不是static,唯一的静态调用是不需要模拟的 StreamSupport 和 Collectors。
  • StreamSupport.stream
  • 这不是你应该首先模拟的调用,它只是一个没有逻辑的通用实用方法,理论上同样可以简单地内联。
  • 那么如何模拟它
  • 解决方案:不要嘲笑!

标签: java spring-boot mockito spring-data-mongodb powermockito


【解决方案1】:

我已经为你提供的方法写了测试。

@RunWith(SpringJunit4ClassRunner.class)
public class MyTestClass
{

@MockBean
private MongoTemplate mongoTemplate;

@MockBean
private MongoCollection<Document> mongoCollection;

@MockBean
private DistinctIterable<String> distinctIterable;

@InjectMocks
private ServiceImpl service;

@Before
public void setUp()throws Exception{
    MockitoAnnotations.openMocks(this);
}

public void testGetTestContent(){
    
    List<String> list = new ArrayList<>();
    list.add("test1");
    list.add("test2");

    Spliterator<String> spliterator = list.spliterator();

PowerMockito.when(mongoTamplate.getCollection(Mockito.eq("test-doc"))).thenReturn(mongoCollection);
PowerMockito.when(mongoCollection.distinct(Mockito.eq("testcontent"),Mockito.eq(String.class))).thenReturn(distinctIterable);
PowerMockito.when(distinctIterable.spliterator()).thenReturn(spliterator);
Assert.assertEquals(2,service.getTestContent().size());
}
}

注意:如果您不想检查返回值的类型,也可以使用 PowerMockito.doReturn(..).when()

【讨论】:

    猜你喜欢
    • 2020-10-08
    • 2017-10-08
    • 2018-03-18
    • 2010-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-24
    • 2017-05-19
    相关资源
    最近更新 更多