mdoTomofumi Chiba
9/13/2024, 10:19:37 AM

Java Spring Mockito: Service クラスのテストのサンプル

Spring あんまり関係ないかも

FooRepository
import org.springframework.stereotype.Repository;

@Repository
public interface FooRepository {
    String find(String id);
}
FooService
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class FooService {
    private final FooRepository fooRepository;
    public String find(String id) {
        return this.fooRepository.find(id);
    }
}
FooServiceTest
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

@ExtendWith(MockitoExtension.class)
public class FooServiceTest {

    @Mock
    private FooRepository fooRepository;

    @InjectMocks
    private FooService fooService;

    @Test
    public void test() {
        when(this.fooRepository.find(any())).thenReturn("mock");
        var actual = this.fooService.find("1");
        assertEquals("mock", actual);
    }
}
TweetBlueskyLike