我对UnitTest和Integration Test有点困惑 我知道下面的代码是集成测试
@RunWith(SpringRunner.class)
@SpringBootTest(classes = LavaMasterApplication.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class CurrencyServiceImplTest {
@Autowired
private CurrencyService currencyService;
static CurrencyDTO currencyDTO = new CurrencyDTO();
@BeforeClass
public static void setUp() {
currencyDTO.setCode("INR");
currencyDTO.setName("Indian Rupee");
currencyDTO.setNumber(12);
}
@Test
public void testA_addCurrency() {
CurrencyDTO dto = currencyService.addCurrency(currencyDTO);
assertThat(dto).isEqualTo(currencyDTO);
}
}
如何为存储库或服务相同的方法编写单元测试用例。我尝试了以下无效的代码段。
@RunWith(MockitoJUnitRunner.class)
public class CurrencyServiceImplUT {
@Mock
CurrencyRepository repository;
@Test
public void testA_addCurrency() {
Currency currency = new Currency();
currency.setCode("IND");
currency.setName("INDIA");
currency.setNumber(1);
// CurrencyRepository currencyRepository = mock(CurrencyRepository.class);
when(repository.save(currency)).thenReturn(currency);
List<Currency> all = repository.findAll();
when(repository.findAll()).thenReturn(null);
}
}
以上代码不起作用,保存实体后返回null,而findAll()也为null。
我需要为存储库和服务编写单元测试用例
答案 0 :(得分:0)
我不知道CurrencyService
的功能以及您在向我们展示的单元测试示例中尝试执行的操作,但是集成测试的等效单元测试将类似于:
public class CurrencyServiceTest {
@Mock
CurrencyRepository repository; // mock the repository
@InjectMocks
CurrencyService service; // use the real implementation and inject the @Mock's on it
@Test
public void testA_addCurrency() {
Currency currency = new Currency();
currency.setCode("IND");
currency.setName("INDIA");
currency.setNumber(1);
when(repository.save(currency)).thenReturn(currency); //mocking the repository return
CurrencyDTO currencyDTO = new CurrencyDTO();
currencyDTO.setCode("INR");
currencyDTO.setName("Indian Rupee");
currencyDTO.setNumber(12);
CurrencyDTO dto = currencyService.addCurrency(currencyDTO);
assertThat(dto).isEqualTo(currencyDTO);
}
}
正如我说的,我无法确定此测试对您是否有意义,但是您的单元测试应该遵循这种代码。