需要为util类(TestInit)方法编写junit测试用例,该方法在内部调用服务方法。
由于util类中的方法调用了服务方法,因此我尝试通过模拟甚至服务调用来编写junit测试。我不确定我是对还是错。
@Repository
public interface TestRepository extends JpaRepository<Test, Integer> {
}
public interface TestService {
public Optional<Test> getTestByCode(String code)
}
@Service
public class TestServiceImpl implements TestService {
@Autowired
private TestRepository testRepo;
@Override
public Optional<Test> getTestByCode(String code) {
return testRepo.findOneByCode(code);
}
}
@Component
public class TestInit {
@Autowired
TestService testService;
private static String value = null;
public boolean isTestAvail() {
value = testService.getTestByCode("test");
return value;
}
}
@RunWith(SpringRunner.class)
public class InitTest {
private TestInit testInit;
private static String value = null;
@TestConfiguration
static class InitTestContextConfiguration {
@Bean
public TestService testService() {
return new TestServiceImpl();
}
}
@Before
public void init() {
testInit = new TestInit();
value = "Random";
}
@MockBean
TestService testService;
@MockBean
private TestRepository testRepository;
@Test
public void testIsSettingsAvaliable() {
when(testRepository.findOneByCode("value")).thenReturn(value);
when(testService.getTestByCode("Value")).thenReturn(value);
assertNotNull(testInit.isTestAvail());
}
}
请有人帮我为util类(TestInit)方法编写junit测试用例,然后再调用service方法。