简体   繁体   English

使用 spring 引导的@MockBean 时创建严格模拟?

[英]Creating strict mock when using @MockBean of spring boot?

I use @MockBean of spring boot (with @RunWith(SpringRunner.class) ) and everything was ok so far.我使用@MockBean引导的 @MockBean(使用@RunWith(SpringRunner.class) ),到目前为止一切正常。
However the mock provides default implementation for every method of the mocked class so I cannot check if only those methods were called that I expected to be called, ie I would like to create strict mock.然而,模拟为模拟 class 的每个方法提供了默认实现,所以我无法检查是否只调用了我期望调用的那些方法,即我想创建严格的模拟。
Is that possible with @MockBean ? @MockBean可以吗?

I don't insist on creating strict mocks if somebody has a good idea how to check if only those methods were called that I expected.如果有人知道如何检查是否只调用了我期望的那些方法,我不会坚持创建严格的模拟。

Thanks for the help in advance!我在这里先向您的帮助表示感谢!

Regards,问候,
V.五、

With Mockito you can verify that a method was called: 使用Mockito,您可以验证方法是否被调用:

verify(mockOne).add("one");

or that it was never called (never() is more readable alias for times(0)): 或者从未调用过(never()是时间(0)的可读别名):

verify(mockOne, never()).remove("two");

Or you can verify that no other method was called: 或者您可以验证没有调用其他方法:

verify(mockOne).add("one"); // check this one
verifyNoMoreInteractions(mockOne); // and nothing else

For more information see the Mockito documentation . 有关更多信息,请参阅Mockito文档

You can use Mockito.verify method for mock object which is created by @Mockbean. 您可以将Mockito.verify方法用于由@Mockbean创建的模拟对象。 It can check that how many times it calls, what argument specified, and so on. 它可以检查它调用了多少次,指定了什么参数,等等。 Please try it. 请试一试。

Here is one way to do it ( quite involved - it may be better to just wait for Mockito 4 where the default will be strict mocks, or wait until after the test finishes using the mock, and then use verifyNoMoreInteractins )这是一种方法(非常复杂 - 最好等待 Mockito 4 ,默认情况下将是严格模拟,或者等到测试完成后使用模拟,然后使用 verifyNoMoreInteractins )

  1. Replace @MockBean with @Autowired with a test configuration with @Primary将@MockBean 替换为@Autowired 并使用@Primary 进行测试配置

  2. Create a default answer that throws an exception for any unstubbed function创建一个默认答案,为任何未存根的 function 抛出异常

Then override that answer with some stubbing - but you have to use doReturn instead of when thenReturn然后用一些存根覆盖那个答案 - 但你必须使用 doReturn 而不是 when thenReturn

// this is the component to mock
@Component
class ExtService {
    int f1(String a) {
        return 777;
    }
}
// this is the test class
@SpringBootTest
@RunWith(SpringRunner.class)
public class ApplicationTests {

    static class RuntimeExceptionAnswer implements Answer<Object> {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            throw new RuntimeException(
                    invocation.getMethod().getName() + " was not stubbed with the received arguments");
        }
    }

    @TestConfiguration
    public static class TestConfig {

        @Bean
        @Primary
        public ExtService mockExtService() {
            ExtService std = Mockito.mock(ExtService.class, new RuntimeExceptionAnswer());
            return std;
        }

    }

    // @MockBean ExtService extService;
    @Autowired
    ExtService extService; // replace mockBean

    @Test
    public void contextLoads() {

        Mockito.doReturn(1).when(extService).f1("abc"); // stubbing has to be in this format
        System.out.println(extService.f1("abc")); // returns 1
        System.out.println(extService.f1("abcd")); // throws exception
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 Spring 启动测试中使用 Strict @MockBean - Strict @MockBean in a Spring Boot Test 在 RabbitMQ Listener 中使用 Spring Boot @MockBean 注解 - Using Spring Boot @MockBean annotation in RabbitMQ Listener @Mock 导致异常但@MockBean 在 spring 启动应用程序中工作 - @Mock results in exception but @MockBean works in spring boot application Spring Boot @MockBean estrange行为 - Spring boot @MockBean estrange behaviour Spring Boot 测试中的 MockBean 注解导致 NoUniqueBeanDefinitionException - MockBean annotation in Spring Boot test causes NoUniqueBeanDefinitionException 如何在 Spring Boot 中将 @MockBean 与 JUnit 5 一起使用? - How to use @MockBean with JUnit 5 in Spring Boot? 注释@MockBean 在 spring 启动 2.3 上不起作用(未注入?) - annotation @MockBean not working(not injected?) on spring boot 2.3 在 Spring 引导中与 OAuth2 一起使用时无法模拟 @PreAuthorize - Cannot mock @PreAuthorize when using with OAuth2 in Spring Boot 运行多个 Spring Boot 测试时,@MockBean 在 JMS 侦听器中使用不同的实例 - @MockBean uses different instance in JMS listener when running multiple Spring Boot tests 如果使用@MockBean,则无法使用ArangoDB-Repository创建Spring-Boot应用程序上下文 - Spring-Boot Application Context with ArangoDB-Repository cannot be created if using @MockBean
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM