【问题标题】:Unable to mock a method which takes an interface无法模拟采用接口的方法
【发布时间】:2020-12-20 05:25:50
【问题描述】:

我的 Spring Boot 项目中有一个服务,其中我有一个采用接口的方法。

interface IT {}
class AService {
 public String method(IT it) {}
}

我有两个实现该接口的类。

class AIT implements IT {}
class BIT implements IT {}

我正在根据我的需要在传递 AIT/BIT 类对象的其他服务中使用此服务方法。

现在,我正在为其他模拟服务的服务编写测试用例

public class OtherServiceTests {

    @MockBean
    private Service service;

  
    @Before
    public void setUp() {
    // none of these mocks working
        Mockito.when(service.method(Mockito.any()))
                .thenReturn("");
    Mockito.when(service.method(Mockito.any(IT.class)))
                .thenReturn("");
    Mockito.when(service.method(Mockito.any(BIT.class)))
                .thenReturn("");
    Mockito.when(service.method(Mockito.any(AIT.class)))
                .thenReturn("");
    // all returing to NullPointerException

    
        otherService = new OtherSerice();
    }

}
 

这些模拟都不适用于这种方法。其他模拟工作正常。它返回 NullPointerException 导致测试失败。

我不熟悉使用 mockito 进行测试。如果有人可以指导我解决这个问题,那么这对我很有帮助。

【问题讨论】:

  • 它是仅对“IT.class”失败,还是对所有三个都失败? "IT.class" 失败是很自然的,因为它内部没有任何方法
  • 所有人都失败了
  • 您正在创建一个可能使用它的新 OtherService,这导致无法将其注入该实例。看起来您在不了解您实际在做什么的情况下混合了很多东西。将 Spring Boot 的东西与模拟混合在一起,而您可能不需要 Spring Boot 的东西。
  • 我强烈建议您使用spock 进行所有测试。它对 Spring Boot 很友好,并提供了超级简单、容易和强大的模拟。恕我直言,一旦你使用它,你将永远不会使用其他任何东西。

标签: java spring-boot unit-testing testing mockito


【解决方案1】:

Mock 未初始化,注解@MockBean 应替换为@Mock。 尝试像这样更改它:

public class AServiceTest {
    @Mock
    AService service;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }
    @Test
    public void myTest(){
        Mockito.when(service.method(Mockito.any())).thenReturn("");
        assertEquals("", service.method(new AIT()));
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-30
    • 2018-06-01
    • 2018-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    相关资源
    最近更新 更多