簡體   English   中英

如何在 Spring Boot 中使用 mockito 模擬 deleteById

[英]How to Mock deleteById using mockito in spring boot

如何在 Spring Boot 中使用 mockito 模擬mockRepository.deleteById()

這取決於你想在哪里使用這個模擬。 對於使用SpringRunner運行的集成測試,可以使用MockBean注釋來注釋存儲庫以模擬。 這個模擬 bean 將自動插入到您的上下文中:

@RunWith(SpringRunner.class)
public class SampleIT {

    @MockBean
    SampleRepository mockRepository;

    @Test
    public void test() {
        // ... execute test logic

        // Then
        verify(mockRepository).deleteById(any()); // check that the method was called
    }
}

對於單元測試,您可以使用MockitoJUnitRunnerMock注釋:

@RunWith(MockitoJUnitRunner.class)
public class SampleTest {

    @Mock
    SampleRepository mockRepository;

    @Test
    public void test() {
        // ... execute the test logic   

        // Then
        verify(mockRepository).deleteById(any()); // check that the method was called
    }
}

deleteById方法返回 void,因此添加模擬注釋並檢查是否調用了模擬方法(如果需要)應該就足夠了。

你可以在這里找到更多信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM