我有一個關于單元測驗的問題。我正在撰寫一個測驗來檢查服務是否正確保存資料(即不重復) 有一個服務類有幾個欄位,我們對 TypeRepository 欄位感興趣。在保存它的方法中呼叫并使用 find 方法......在這種情況下,當我運行測驗時,我得到 NullPointerException。我不知道在這種情況下有什么幫助。我將不勝感激
服務
@Service
@Slf4j
public class Service {
...
...
final RiskRepo riskRepo;
...
...
private Limit validate(Limit newLimit) {
RiskType.Value typeValue
= riskRepo.findDistinctLimitTypeValueByLimitType(newLimitType);
// ^--- exception
switch (typeValue) { <-- warning can be null
case CONTY: {
...
break;
}
...
}
回購
public interface Repo extends JpaRepository<Limit, Integer> {
@Query("SELECT DISTINCT r.Value from Type r WHERE r.limit=?1")
RiskType.Value findDistinctValueByLimit(String limitType);
}
測驗
@Test
public void test_validate() {
Limit newLimit = Limit.builder()
.riskType(...)
......build();
limitService.create(newLimit);
List<Limit> limits = limitRepository.findAllByRiskTypeAndEntityAndLimitTypeAndUnitAndActive(
newLimit.getRiskType(), newLimit.getEntity(), newLimit.getLimitType(),newLimit.getUnit(),newLimit.getActive());
Assert.assertEquals(1, limits.size());
}
uj5u.com熱心網友回復:
您可以撰寫更多測驗類的代碼,因為它可能是測驗配置問題或不在這些代碼段上的問題。但首先,確保您在服務上注入存盤庫,它看起來不像,所以使用 @Autowired 注釋存盤庫屬性或創建一個建構式并在他內部啟動存盤庫實體。可能導致問題的另一件事是您的服務方法是私有的,它需要是公共的,否則只有服務類可以訪問它。
關于測驗,通常當我做這些測驗時,它們可以被模擬或集成。
模擬測驗:
您必須在服務測驗類上方使用諸如 @RunWith(MockitoJunitRunner.class) 之類的注釋。然后注入服務并使用@Mock(repo)和@InjectMocks(服務)模擬您正在使用的存盤庫。
@RunWith(MockitoJUnitRunner.class)
public class YourTestClass {
@InjectMocks
private LimitService service;
@Mock
private LimitRepository repository;
@Test
public void test_validate(){
when(this.repository...).thenReturn(...);
this.service.doSomething();
verify(this.repository).doSomething(...);
verifyNoMoreInteractions(this.repository);
}
集成測驗:
在這里,您要做的幾乎與存盤庫測驗相同,不同之處在于您將需要呼叫將呼叫存盤庫方法的 SERVICE。您需要配置您的類以像存盤庫測驗一樣運行背景關系。
@RunWith(SpringRunner.class)
@SpringBootTest
public class EmployeeRestControllerIntegrationTest {
@Autowired
private LimitService service;
// write test cases here (such as your own, asserting the result of the service method return)
}
所以這些將是這兩種服務測驗的解決方案,現在如果你需要測驗存盤庫,我建議查看 Spring Boot 存盤庫測驗。
uj5u.com熱心網友回復:
我能夠通過使用@Before 方法初始化存盤庫并將測驗資料寫入資料庫來解決問題
@Before
public void setup() {
Type type = new Type(
data..);
TypeRepository.save(type);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/415652.html
標籤:
上一篇:DoseWebApplicationContext和ServletApplicationContext是一回事嗎?
