問題描述
我的單元測試中有任何問題,我有類似的東西.如果 blargh
函數使用 Transactional 注釋,則模擬注入會在 someService 上被覆蓋.如果我刪除 Transactional ,則模擬會留在那里.從代碼中可以看出,當服務中的函數被注釋為事務時,Spring 會延遲加載服務,但在沒有注釋時會急切地加載服務.這會覆蓋我注入的模擬.
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();
}
}
推薦答案
或許您可以嘗試通過以下方式實現您的測試:
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.
這篇關于如何將模擬注入具有@Transactional 的@Service的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!