Skip to content

@MockBean causes mybatis to fail to read mappers #667

Open
@djors

Description

@djors

dear developers,
here's the issues we are faced with.
1 mybatis mappers cannot be loaded when spring container reloads
2 connection is not configured correctly when spring container reloads

mybatis mappers cannot be loaded when spring container reloads

our project is using mybatis coupled with spring boot. currently we are implementing spring integration tests.
there are some cases we need to use @MockBean to do some data mocking.
we find @MockBean causes spring container to refresh (reload) which is something what spring is supposed to do according to this post.
https://stackoverflow.com/questions/45587213/using-mockbean-in-tests-forces-reloading-of-application-context
however meanwhile mybatis is not able to read its mappers in the second launch.

as far as we can figure out, there's a class called TableInfoHelper that has a static field TABLE_INFO_CACHE for cache.
when spring container reloads, TABLE_INFO_CACHE is not cleared so it prevents mappers from being loaded again.

connection is not configured correctly when spring container reloads

this issue is associated with the first one. we use reflection to clear the TABLE_INFO_CACHE as a workaround to reload mappers which works somehow.
however when mybatis reloads again, it uses a transaction that is auto-commit which causes data created by our test cases not to be rollbacked.
unfortunately we don't have done too much investigation regarding this issue. we are going to provide some examples which may help you to understand this problem.
suppose the following 3 classes will run in the order of Test1, Test2, Test3

@ExtendWith(SpringExtenson.class)
@SpringBootTest
@Transactional
class Test1 {
  @Test
  test1() {
     // insert a record. id is 100
     // data gets rollbacked after the case
  }

}


@ExtendWith(SpringExtenson.class)
@SpringBootTest
@Transactional
class Test2 {
  @MockBean
  private SomeBean someBean;  // this will cause spring to reload

  @Test
  test2() {
     // some code
  }

}


@ExtendWith(SpringExtenson.class)
@SpringBootTest
@Transactional
class Test3 {

  @Test
  test3() {
     // insert a record, id is 100.
  }

  @Test
  test3_2() {
    // insert a record
    // failed. 100 already exists. so test3 doesn't get rollbacked.
    // as we debug, we have found the connection in test3 is strangely configured. auto-commit is true.
  }

}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions