When I call method from Test I have Always null resolte - spring-boot

I have test class ExecuteTest and I want to test the method returnString method who is in MyStringClass, and in returnString I call strings() from class OtherString.
This is my code:
#RunWith(MockitoJUnitRunner.class)
public class ExecuteTest {
#InjectMocks
private MyStringClass myStringClass;
#Mock
private OtherString otherString;
#Before
public void init() {
MockitoAnnotations.initMocks(this);
}
#Test
public void testString() {
String test = myStringClass.returnString("test");
assertThat(test, equalTo(test));
}
}
#Service
public class MyStringClass {
#Autowired
private OtherString otherString;
public <T extends Object> T returnString(String key) {
return (T) otherString.strings(key);
}
}
And my test variable is always null in my test.

Related

Spring Boot Test model attribute does not exist

Im trying to test a controller, Author Controller, which returns a view with a model. The problem is on the testInitUpdateAuthor() test where its not able to find the model or attribute name specifically. All other methods are fine with their model/attribute tests.
Any advice?
#Slf4j
#Controller
public class AuthorController {
private final AuthorService authorService;
private final String CREATEORUPDATEFORM = "author/createOrUpdateAuthor";
public AuthorController(AuthorService authorService) {
this.authorService = authorService;
}
#GetMapping("/author/{id}/update")
public String updateAuthor(#PathVariable("id") Long id, Model model) {
model.addAttribute("author", authorService.findById(id));
return CREATEORUPDATEFORM;
}
#ExtendWith(MockitoExtension.class)
#SpringBootTest
class AuthorControllerTest {
MockMvc mockMvc;
#Mock
AuthorService authorService;
#InjectMocks
AuthorController authorController;
#BeforeEach
void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(authorController).build();
}
#Test
void getIndex() throws Exception {
mockMvc.perform(get("/author/index"))
.andExpect(status().isOk())
.andExpect(view().name("author/index"))
.andExpect(model().attributeExists("authors"));
}
#Test
void testInitUpdateAuthor() throws Exception {
when(authorService.findById(anyLong())).thenReturn(Author.builder().id(1L).build());
mockMvc.perform(get("/author/1/update"))
.andExpect(status().isOk())
.andExpect(view().name("author/createOrUpdateAuthor"))
.andExpect(model().attributeExists("author"));
}
}

Mocking a service in a Testcontainer Spring boot test

I am quite new in Spring and I am facing an issue right now with testing:
I have the following Service:
#Service
public class MyService {
public Integer getKey() {
List<Integer> keys = getKeys(1);
if (keys.size() == 1) {
return keys.get(0);
}
throw new IllegalArgumentException("Error!");
}
... and a getKeys() method, which provides a list based ona rest call...
}
And I use this service class in antother class:
#NoArgsConstructor
public class MyOtherClass extends MyClass {
#Autowired
private MyService myService;
....
#Override public KeyValue<Object, Object> doSomething(Object key, Object value) {
if (conditionIsTrue(key, value)) {
MyObject obj = new MyObject();
myObject.setKey(keyService.getKey()); ----- here is always null the keyService
.....
} else {
return KeyValue.pair(null, null);
}
}
And I try to write a test but the MyService is always null..
#ActiveProfiles("my-test")
#SpringBootTest(classes = Application.class)
#Testcontainers
#Slf4j
public class MyTest extends TestContext {
#BeforeEach
void init(final TestInfo testInfo) {
....
}
#AfterEach
void deinit() {
....
}
#Test
public void myTest() {
....
}
How can I inject a mock MyService into the test container?
Thank you!

JUNIT - Null pointer Exception while calling findAll in spring Data JPA

I am new to Junits and Mockito, I am writing a Unit test class to test my service class CourseService.java which is calling findAll() method of CourseRepository.class which implements CrudRepository<Topics,Long>
Service Class
#Service
public class CourseService {
#Autowired
CourseRepository courseRepository;
public void setCourseRepository(CourseRepository courseRepository) {
this.courseRepository = courseRepository;
}
public Boolean getAllTopics() {
ArrayList<Topics> topicList=(ArrayList<Topics>) courseRepository.findAll();
if(topicList.isEmpty())
{
return false;
}
return true;
}
}
Repository class
public interface CourseRepository extends CrudRepository<Topics,Long>{
}
Domain class
#Entity
#Table(name="Book")
public class Topics {
#Id
#Column(name="Topicid")
private long topicId;
#Column(name="Topictitle",nullable=false)
private String topicTitle;
#Column(name="Topicauthor",nullable=false)
private String topicAuthor;
public long getTopicId() {
return topicId;
}
public void setTopicId(long topicId) {
this.topicId = topicId;
}
public String getTopicTitle() {
return topicTitle;
}
public void setTopicTitle(String topicTitle) {
this.topicTitle = topicTitle;
}
public String getTopicAuthor() {
return topicAuthor;
}
public void setTopicAuthor(String topicAuthor) {
this.topicAuthor = topicAuthor;
}
public Topics(long topicId, String topicTitle, String topicAuthor) {
super();
this.topicId = topicId;
this.topicTitle = topicTitle;
this.topicAuthor = topicAuthor;
}
}
Following is the Junit class I have written but courseRepository is getting initialized to NULL and hence I am getting NullPointerException.
public class CourseServiceTest {
#Mock
private CourseRepository courseRepository;
#InjectMocks
private CourseService courseService;
Topics topics;
#Mock
private Iterable<Topics> topicsList;
#Before
public void setUp() {
MockitoAnnotations.initMocks(CourseServiceTest.class);
}
#Test
public void test_Get_Topic_Details() {
List<Topics> topics = new ArrayList<Topics>();
Mockito.when(courseRepository.findAll()).thenReturn(topics);
boolean result=courseService.getAllTopics();
assertTrue(result);
}
}
Change the setUp() method to:
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
Probably you are dealing with some problem on the framework to make the mocked class be injected by the framework.
I recommend to use Constructor Injection, so you don't need to rely on the reflection and #Inject/#Mock annotations to make this work:
#Service
public class CourseService {
private final CourseRepository courseRepository;
// #Autowired annotation is optional when using constructor injection
CourseService (CourseRepository courseRepository) {
this.courseRepository = courseRepository;
}
// .... code
}
The test:
#Test
public void test_Get_Topic_Details() {
List<Topics> topics = new ArrayList<Topics>();
Mockito.when(courseRepository.findAll()).thenReturn(topics);
CourseService courseService = new CourseService(courseRepository);
boolean result = courseService.getAllTopics();
assertTrue(result);
}

How to write junit test for below code using mockito?

Hi I am new to groovy unit test using mockito.I am trying to figure how to write test case for daoImpl calss without really updating or inserting in database.
below is my code.
#Component
public class TransactionDAOImpl implements TransactionDAO {
#Autowired
StringUtilities stringUtilities;
#Autowired
private TransactionRepository transactionRespository;
#Override
#Transactional
public String create(List<DepositoryTransaction> depositoryTransaction) {
List<DepositoryTransaction> dep = transactionRespository.saveAll(depositoryTransaction);
LOGGER.debug("Recieved atm transaction : {} = {}", dep);
if (dep != null && !dep.isEmpty())
return stringUtilities.SUCCESS;
else
return stringUtilities.FAILURE;
}
}
#RunWith(MockitoJUnitRunner.class) // org.mockito.runners.MockitoJUnitRunner is deprecated so use org.mockito.junit.MockitoJUnitRunner instead
public class TransactionDAOImplTest{
#InjectMocks
private TransactionDAOImpl transactionDAOImpl;
#Mock
StringUtilities stringUtilities;
#Mock
private TransactionRepository transactionRespository;
List<DepositoryTransaction> depositoryTransaction=new ArrayList<>();
#Test
public void testCreateSaveAllNullReturn(){
when(transactionRespository.saveAll(depositoryTransaction)).thenReturn(null);
assertThat(transactionDAOImpl.create(depositoryTransaction)).isEqualTo(stringUtilities.SUCCESS); // i do not khnow if this is an enum ?
}
#Test
public void testCreateSaveAllEmptyReturn(){
when(transactionRespository.saveAll(depositoryTransaction)).thenReturn(new ArrayList<>());
assertThat(transactionDAOImpl.create(depositoryTransaction)).isEqualTo(stringUtilities.SUCCESS); // i do not khnow if this is an enum ?
}
#Test
public void testCreateSaveAllNotEmptyAndNotNullReturn(){
DepositoryTransaction obj=new DepositoryTransaction();
depositoryTransaction.add(obj);
when(transactionRespository.saveAll(depositoryTransaction)).thenReturn(depositoryTransaction);
assertThat(transactionDAOImpl.create(depositoryTransaction)).isEqualTo(stringUtilities.FAILURE); // i do not khnow if this is an enum ?
}
}

How to inject a bean in a ConstraintValidator with MockMVC?

I have a custom ConstraintValidator:
#Component
public class FooValidator implements ConstraintValidator<FooAnnotation, String> {
#Inject
private FooRepository fooRepository;
#Override
public void initialize(FooAnnotation foo) {
}
#Override
public boolean isValid(String code, ConstraintValidatorContext context) {
Foo foo = fooRepository.findByCode(code);
//My code
}
}
In my Junit tests and MockMVC I call the url but fooRepository bean validator is always null.
How I can inject it in my test controller? I tried to create a mock repository but it is also null.
My source code test:
public class FooControllerTest {
#InjectMocks
private FooController fooController;
private MockMvc mockMvc;
#Before
public void setup() {
// Process mock annotations
MockitoAnnotations.initMocks(this);
// Setup Spring test in standalone mode
this.mockMvc = MockMvcBuilders.standaloneSetup(fooController)
.setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver())
.build();
}
#Test
public void testSave() throws Exception {
Foo foo = new Foo();
// given
//My code...
// when
// then
// with errors
this.mockMvc.perform(post("/foo/update")
.param("name", "asdfasd")
.sessionAttr("foo", foo))
.andExpect(model().hasErrors())
.andExpect(model().attributeHasFieldErrors("foo", "name"));
}
}
You should add a #ContextConfiguration to your test, among other things.

Resources