简体   繁体   English

Mockito 测试单独通过但作为套件的一部分失败

[英]Mockito Tests Pass individually but fail as part of a suite

I have a case where my mockito tests all pass individually but can fail when run as part of a testing suite.我有一个案例,我的模拟测试全部单独通过,但作为测试套件的一部分运行时可能会失败。 I am using mockito version 2.9.0我正在使用 mockito 版本 2.9.0

My test class is as follows我的测试类如下

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.BDDMockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import com.cache.CacheServices;

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(value={"classpath:generalConfig/generalConfigMocks-context.xml"})
public class GeneralConfigAPIClientTest {

    private MockMvc mockMvc;

    @Autowired
    CacheServices cacheServices; 

    @Autowired
    IGeneralConfigServices generalConfigServices;

    @Autowired 
    private WebApplicationContext wac;

    /**
     * Set up the test context, initialize the mockMvc.
     * */
    @Before 
    public void setUp() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();       
    }

    @Test
    public void testEmptyGeneralConfigCache_FailureFalseReturned() throws Exception {

        BDDMockito.given(cacheServices.emptyCacheContents(BDDMockito.anyString())).willReturn(false);

        this.mockMvc.perform(get("/generalConfig/emptyGeneralConfigCache"))
                .andExpect(status().isOk())     
                .andReturn();

        BDDMockito.verify(cacheServices, BDDMockito.times(1)).emptyCacheContents(BDDMockito.anyString());
    }

    @Test
    public void testEmptyGeneralConfigCache_SuccessTrueReturned() throws Exception {
        BDDMockito.given(cacheServices.emptyCacheContents(BDDMockito.anyString())).willReturn(true);

        this.mockMvc.perform(get("/generalConfig/emptyGeneralConfigCache"))
                .andExpect(status().isOk())     
                .andReturn();

        BDDMockito.verify(cacheServices, BDDMockito.times(1)).emptyCacheContents(BDDMockito.anyString());
    }

    }

The contents of generalConfig/generalConfigMocks-context.xml are as follows generalConfig/generalConfigMocks-context.xml 的内容如下

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:oxm="http://www.springframework.org/schema/oxm"
    xmlns:util="http://www.springframework.org/schema/util" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:ehcache="http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring"
    xmlns:cache="http://www.springframework.org/schema/cache"
    xsi:schemaLocation="
   http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
   http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
   http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.1.xsd
   http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring
   http://ehcache-spring-annotations.googlecode.com/svn/schema/ehcache-spring/ehcache-spring-1.1.xsd
   http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.1.xsd
   http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <mvc:annotation-driven />

    <context:annotation-config />

    <context:component-scan base-package="com..config" />

    <bean id="generalConfigServices" class="org.mockito.BDDMockito" factory-method="mock">
        <constructor-arg value="com.config.IGeneralConfigServices"/>
    </bean>


    <bean id="cacheServices" class="org.mockito.BDDMockito" factory-method="mock">
        <constructor-arg value="com.cache.CacheServices"/>
    </bean>


</beans>

A sample error response I get from running my tests is as follows我从运行测试中得到的示例错误响应如下

    org.mockito.exceptions.verification.TooManyActualInvocations: 
cacheServices.emptyCacheContents(
    <any string>
);
Wanted 1 time:
-> at com.config.GeneralConfigAPIClientTest.testEmptyGeneralConfigCache_SuccessTrueReturned(GeneralConfigAPIClientTest.java:65)
But was 2 times. Undesired invocation:
-> at com.config.GeneralConfigAPIClient.callEmptyGeneralConfigCache(GeneralConfigAPIClient.java:34)

    at com.config.GeneralConfigAPIClientTest.testEmptyGeneralConfigCache_SuccessTrueReturned(GeneralConfigAPIClientTest.java:65)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:539)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:761)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:461)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:207)

Can anyone offer any insights as to why my tests are passing individually but failing as a group任何人都可以提供有关为什么我的测试单独通过但作为一个组失败的任何见解

Reason: your test load one application context with bean mock inside. 原因:您的测试在内部使用bean mock加载一个应用程序上下文。 The bean mocks are dirty after any test. 任何测试后豆粪都很脏。 You have a dirty application context also. 您也有一个脏的应用程序上下文。

Solution: you have to clean bean mock. 解决方案:你必须清理bean mock。 Using Mockito.reset(mocks) after each test. 每次测试后使用Mockito.reset(模拟)。 I've found sth similar: How to clean up mocks in spring tests when using Mockito 我发现类似: 如何在使用Mockito时在弹簧测试中清理模拟

I am late in the game, but thought that this could be useful for people that are still experiencing the same issue(source: https://reflectoring.io/clean-unit-tests-with-mockito/ ):我在游戏中迟到了,但认为这对仍然遇到相同问题的人可能有用(来源: https : //reflectoring.io/clean-unit-tests-with-mockito/ ):

class CityServiceImplTest {

  // System under Test (SuT)
  private CityService cityService;

  // Mock
  private CityRepository cityRepository;

  @BeforeEach
  void setUp() {
    cityRepository = Mockito.mock(CityRepository.class);
    cityService = new CityServiceImpl(cityRepository);
  }

  // Test cases omitted for brevity.

}

With this approach, I eliminated the @SpringBootTest annotation altogether and made the test class very light weight.通过这种方法,我完全消除了 @SpringBootTest 注释,并使测试类的重量非常轻。

I faced with this problem too and solved the problem like this;我也遇到了这个问题,解决了这个问题;

Added these 3 annotations to my test classs:将这 3 个注释添加到我的测试类中:

@RunWith(SpringRunner.class)
@TestPropertySource(properties = {
        "spring.jpa.hibernate.ddl-auto=none"
})
@SpringBootTest

Created Mocks with:创建的模拟:

@InjectMocks
private ImplService service;

@Mock
private MailService mailService;

In the set up:在设置中:

    @Before
    public void setUp() {
        LockAssert.TestHelper.makeAllAssertsPass(true);
        MockitoAnnotations.initMocks(this);
        // In case if you are using "environment" in your  
        ReflectionTestUtils.setField(service, "environment", "testEnvironment");
        ....
    }

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

相关问题 如果作为测试套件的一部分运行,JUnit测试将失败 - JUnit tests fail if run as part of a test suite TestNG 测试用例单独通过,但在作为测试套件运行时失败 - TestNG test cases pass individually, but fail when running as a test suite Selenium Eclipse Test Suite测试在套件中失败,但在单独运行时成功 - Selenium Eclipse Test Suite tests fail in the suite, but are successful when run individually JUnit测试在一起运行时失败,但是单独传递 - JUnit tests fail when run together, but pass individually 春季单元测试失败为组,但单独通过 - Spring-run Unit Tests Fail as Group, but Pass Individually 为什么我的测试一起运行时通过,但单独失败? - Why do my tests pass when run together, but fail individually? Maven故障安全插件重新运行套件中的各个失败测试 - Maven fail-safe plugin rerunning individual failing tests that are part of a suite TestNG 测试在作为 Maven 测试运行时失败,但在作为 TestNG 套件运行时通过 - TestNG tests fail when ran as Maven Test, but pass when running as TestNG suite JUnit:运行套件和单独运行测试之间有什么区别吗? - JUnit: Is there any difference between running a Suite, and running tests individually? 如何找到不属于任何套件的单元测试? - How to find unit tests not part of any suite?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM