Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

java - How to inject mock into @Service that has @Transactional

I have any issue in my unit test where I have something along the lines of this. The mock injection get overridden on the someService if the blargh function is annotated with Transactional. If I remove the Transactional the mock stays there. From watching the code it appears that Spring lazily loads the services when a function in the service is annotated with transactinal, but eagerly loads the services when it isn't. This overrides the mock I injected.

Is there a better way to do this?

@Component
public class SomeTests
{
  @Autowired
  private SomeService someService;

  @Test
  @Transactional
  public void test(){
    FooBar fooBarMock = mock(FooBar.class);
    ReflectionTestUtils.setField(someService, "fooBar", fooBarMock);
  }
}

@Service
public class someService
{
  @Autowired FooBar foobar;

  @Transactional // <-- this causes the mocked item to be overridden
  public void blargh()
  {
    fooBar.doStuff();
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Probably you could try to implement your test in the following way:

@Component
@RunWith(MockitoJUnitRunner.class)
public class SomeTests
{
  @Mock private FooBar foobar;
  @InjectMocks private final SomeService someService = new SomeService();


  @Test
  @Transactional
  public void test(){
    when(fooBar.doStuff()).then....;
    someService.blargh() .....
  }
}

I could not try it right now as don't have your config and related code. But this is one of the common way to test the service logic.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...