我在我的Sping Boot 应用程序中为我的服务编写了一个JUnit 5测试。我使用@MockBean
来模拟PasswordEncoder
和其他bean,但是我得到了一个NullPointerException
。
在when
调用期间,我总是获得一个NullPointerException:when(compteRepository.getByLogin(anyString())).thenReturn(Optional.of(acc));
服务
package com.compte.application.impl;
import com.compte.application.CompteService;
import com.compte.domain.exceptions.EntityNotFoundExcpetion;
import com.compte.domain.model.Compte;
import com.compte.domain.model.CompteUpdatedData;
import com.compte.domain.repository.CompteRepository;
import com.compte.domain.utils.CompteUtil;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.crypto.password.PasswordEncoder;
import java.time.LocalDate;
import java.util.Optional;
/**
* @author mbint
*/
@AllArgsConstructor
public class CompteServiceImpl implements CompteService{
private final static Logger LOGGER = LoggerFactory.getLogger(CompteService.class);
private CompteRepository CompteRepository;
private PasswordEncoder passwordEncoder;
@Override
public Optional<Compte> getByLogin(String login) {
return CompteRepository.getByLogin(login);
}
@Override
public void update(final Long id, CompteUpdatedData updatedData) {
Optional<Compte> optional = CompteRepository.getById(id);
if(optional.isPresent()) {
Compte Compte = optional.get();
Compte.setFirstName(updatedData.getFirstName());
Compte.setLastName(updatedData.getLastName());
CompteRepository.save(Compte);
} else {
throw new EntityNotFoundExcpetion("Compte: " + id + " not found !!");
}
}
}
Junit测试
package com.compte.application;
import com.compte.application.impl.CompteServiceImpl;
import com.compte.domain.model.Compte;
import com.compte.domain.model.CompteUpdatedData;
import com.compte.domain.repository.compteRepository;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.security.crypto.password.PasswordEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static org.mockito.Mockito.*;
/**
* @author mbint
*/
public class CompteServiceImplTest {
private final static String PASSWORD = "Passw00rd";
@MockBean
private compteRepository compteRepository;
@MockBean
private PasswordEncoder passwordEncoder;
private CompteService CompteService = new CompteServiceImpl(compteRepository, passwordEncoder);
@DisplayName(("Should return existing user"))
@Test
private void given_login_then_return_existing_user() {
Compte acc = Compte.builder().id(1L)
.firstName("Luc")
.lastName("JOJO")
.login("xxx@gmail.com")
.password("xxxxxxxxxxxxxxx")
.build();
when(compteRepository.getByLogin(anyString())).thenReturn(Optional.of(acc));
Optional<Compte> optional = CompteService.getByLogin("xxx@gmail.com");
Compte Compte = optional.get();
Assertions.assertSame(1L, acc.getId());
Assertions.assertSame("xxx@gmail.com", Compte.getLogin());
}
@DisplayName("Should update existing user")
@Test
public void given_edited_Compte_then_update_user() {
Compte acc = Compte.builder().id(1L)
.firstName("Luc")
.lastName("JOJO")
.email("xxx@gmail.com")
.password("xxxxxxxxxxxxxxx")
.build();
when(compteRepository.getById(anyLong())).thenReturn(Optional.of(acc));
CompteUpdatedData updatedData = CompteUpdatedData.builder()
.firstName("Moos")
.lastName("Man")
.build();
CompteService.update(1L, updatedData);
Assertions.assertSame("Moos", acc.getFirstName());
}
private List<Compte> getComptes() {
List<Compte> Comptes = new ArrayList<>();
Compte acc1 = Compte.builder()
.id(1L)
.firstName("Luc")
.lastName("JOJO")
.email("xxx@gmail.com")
.login("xxx@gmail.com")
.build();
Comptes.add(acc1);
Compte acc2= Compte.builder()
.id(2L)
.firstName("Jean")
.lastName("KELLY")
.email("jean.kelly@gmail.com")
.login("jean.kelly@gmail.com")
.build();
Comptes.add(acc2);
Compte acc3= Compte.builder()
.id(3L)
.firstName("Marc")
.lastName("BARBY")
.email("marc.barby@gmail.com")
.login("marc.barby@gmail.com")
.build();
Comptes.add(acc3);
return Comptes;
}
}
Spring Boot 应用
package com.compte;
import com.compte.application.CompteService;
import com.compte.application.impl.CompteServiceImpl;
import com.compte.domain.repository.CompteRepository;
import com.compte.infrastructure.repository.database.CompteDBRepositiry;
import com.ombsc.bargo.common.config.SwaggerConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
import org.springframework.hateoas.client.LinkDiscoverer;
import org.springframework.hateoas.client.LinkDiscoverers;
import org.springframework.hateoas.mediatype.collectionjson.CollectionJsonLinkDiscoverer;
import org.springframework.plugin.core.SimplePluginRegistry;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import java.util.ArrayList;
import java.util.List;
@ComponentScan({"com.compte.interfaces.interfaces"})
@SpringBootApplication
@Import({SwaggerConfig.class})
public class CompteApplication {
public static void main(String[] args) {
SpringApplication.run(CompteApplication.class, args);
}
@Bean
public CompteRepository getRepository() {
return new CompteDBRepositiry();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public CompteService CompteService(CompteRepository repository, PasswordEncoder passwordEncoder) {
return new CompteServiceImpl(repository, passwordEncoder);
}
@Bean
public LinkDiscoverers discovers() {
List<LinkDiscoverer> plugins = new ArrayList<>();
plugins.add(new CollectionJsonLinkDiscoverer());
return new LinkDiscoverers(SimplePluginRegistry.create(plugins));
}
}
1条答案
按热度按时间mhd8tkvw1#
在使用模拟之前,需要初始化它们。有几个选项可以完成此操作。
第一个选项是使用
@SpringExtension
,它将初始化用@MockBean
注解的mock:这将确保在自动连接服务Bean之前模拟存储库Bean。
但是,由于您正在为服务编写单元测试,因此根本不需要Spring扩展。第二种选择是使用
@Mock
而不是@MockBean
,并结合MockitoExtension
调用@InjectMocks
来构造被测服务:或者,您可以只调用
MockitoAnnotations.initMocks()
,它将初始化用@Mock
注解的mock,并为您的服务使用构造函数注入:最后,您可以直接调用
Mockito.mock()
,而无需注解: