簡體   English   中英

如何驗證mockito是否從其他方法調用了方法

[英]How to verify if method was called from other by mockito

我試圖模擬一個在另一個內部調用的方法的行為,以便它模擬一個對象的返回,另一個時間它引發一個異常,但如果確切的話,它是否可能,以及它是否可能。

@Service
@Transactional
public class CategoryService {

    @Autowired
    private CategoryRepository repository;

    public Category findById(Integer id) {
        Optional<Category> obj = repository.findById(id);
        return obj.orElseThrow(() -> new ObjectNotFoundException(id.toString()));
    }


    public Category update(Category category){
        // Throws ObjectNotFoundException if not found before update
        this.findById(category.getId());
        return repository.save(category);
    }

}


@RunWith(MockitoJUnitRunner.class)
public class CategoryServiceUnitTest {

    @Mock
    private CategoryService service;

    @Test()
    public void Should_UpdateCategory_When_FindCategory() {
        Category cat = new Category(1, "Test");
        //Is it possible?
        when(service.findById(Mockito.anyInt())).thenReturn(cat);

        Category category = service.update(cat);
        assertThat(category.getName()).isEqualTo(cat.getName());

        verify(service, times(1)).update(cat);
    }

    @Test(expected = ObjectNotFoundException.class)
    public void Should_ThrowsObjectNotFoundException_When_NotFoudCategoryById() {
        Category cat = new Category(1, "Test");
        //Is it possible?
        when(service.findById(Mockito.anyInt())).thenThrow(ObjectNotFoundException.class);

        service.update(cat);
    }

}

正如評論中指出的那樣,您要做的是在測試中模擬CategoryRepository

@RunWith(MockitoJUnitRunner.class)
public class CategoryServiceTest {

    private CategoryService service;

    @Mock
    private CategoryRepository repository;

    @Before
    public void setup() {
        service = spy(new CategoryService(repository));
    }

    @Test
    public void Should_UpdateCategory_When_FindCategory() throws ObjectNotFoundException {
        Category cat = new Category(1, "Test");

        when(repository.findById(Mockito.anyLong())).thenReturn(Optional.of(cat));
        //return the category object that is used to call the repository.save(...) method
        when(repository.save(Mockito.any(Category.class)))
                .thenAnswer((Answer<Category>) invocation -> {
                            Object[] args = invocation.getArguments();
                            return (Category) args[0];
                        }
                );
        //depending on your requirements the above might be overkill, just replace that logic with this
        //when(repository.save(Mockito.any(Category.class))).thenReturn(cat);

        Category category = service.update(cat);

        assertThat(category).isNotNull();
        assertThat(category.getName()).isEqualTo(cat.getName());

        verify(service).update(cat);
    }

    @Test(expected = ObjectNotFoundException.class)
    public void Should_ThrowsObjectNotFoundException_When_NotFoudCategoryById() throws ObjectNotFoundException {
        Category cat = new Category(1, "Test");

        when(service.findById(Mockito.anyLong())).thenThrow(ObjectNotFoundException.class);

        service.update(cat);
    }
}

您還需要處理已檢查的異常ObjectNotFoundException 我剛剛在方法簽名中添加了異常,您可能希望在生產設置中以不同方式處理它

@Service
@Transactional
public class CategoryService {

    private final CategoryRepository repository;

    @Autowired
    public CategoryService(CategoryRepository repository) {
        this.repository = repository;
    }

    public Category findById(Long id) throws ObjectNotFoundException {
        Optional<Category> obj = repository.findById(id);
        return obj.orElseThrow(() -> new ObjectNotFoundException(id.toString()));
    }

    public Category update(Category category) throws ObjectNotFoundException {
        // Throws ObjectNotFoundException if not found before update
        this.findById(category.getId());
        return repository.save(category);
    }
}

暫無
暫無

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

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