Mockito mock objects returns null
It really depends on GeneralConfigService#getInstance() implementation. Also you can simplify your test code a lot if you use @InjectMocks
annotation.
When using MockitoJUnitRunner
you don't need to initialize mocks and inject your dependencies manually:
@RunWith(MockitoJUnitRunner.class)
public class GeneralConfigServiceImplTest {
@InjectMocks
private GeneralConfigService generalConfigService;
@Mock
private GeneralConfigDAO generalConfigDAO;
@Test
public void testAddGeneralConfigCallDAOSuccess() {
// generalConfigService is already instantiated and populated with dependencies here
...
}
}
Mocked object returning null
From the comments you tell that Connector4AuroraDB
is autowired by Spring(@Autowired
).
It seems to me that you are using field injections, which makes it difficult to do stub dependencies.
I assume you have something like:
public class AuroraRepoImpl {
@Autowired private Connector4AuroraDB connector4AuroraDB;
}
For this to work you need a Spring context setup, so spring can look into the bean registry to find the dependency.
Your example is a simple unit test running with MockitoJUnitRunner
.
You should change your implementation to use injection by constructor, this way Mockito can inject the dependency:
public class AuroraRepoImpl {
private final Connector4AuroraDB connector;
@Autowired
public AuroraRepoImpl(final Connector4AuroraDB connector) {
this.connector = connector;
}
}
If you use a new Spring version you can even omit the @Autowired
annotation if the class only has one constructor.
Why does Mockito return null when I specify an Optional of my type
I believe it is because you forget to mock the method PunishmentValidator#validatePunishmentName("mute")
to return true
such that the method that you stub on PunishmentService
is never invoked because by default if you do not stub a method , it will return false (see this).
Also it is a known behaviour that @MockBean
is configured as lenient stubbing which will not reported error (i.e. throw UnnecessaryStubbingException
) if you stub a method but it actually does not get executed.
So change the following should fix your problem :
@Test
public void getPunishmentTypeReturnsMuteWhenMuteIsSpecified() throws Exception {
Optional<Punishment> mute = Optional.of(new Punishment("mute"));
Mockito.when(punishmentService.getPunishmentType("mute")).thenReturn(mute);
Mockito.when(punishmentValidator.validatePunishmentName("mute")).thenReturn(true);
mvc.perform(get("/api/punishments/mute"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.punishmentName", Matchers.equalTo("mute")));
}
Mockito Mocked Class returns Null
The way to use Mockito is
private DescribeHiveTable mockObj; // must be accessible to Test methods
@Before
public void initialize(){
this.mockObj = Mockito.mock(DescribeHiveTable.class);
<etc>
}
@Test
public void testComplexFeaturesExistingRun() {
/* test the objects that are set up to use this.mockObj,
and not the usual type of DescribeHiveTable */
}
Note that
describeTable = new DescribeHiveTable();
means that you're using a new, unmocked, DescribeHiveTable
, not the mocked mockObj
.
But it looks like you don't have control over the DescribeHiveTable
instance used by the DriverClass
? If that's the case then either
- Mockito isn't going to help you -- or you at least have to mock the
DriverClass
too; or - you have to use reflection to replace the
describeTable
inDriverClass
withmockObj
.
Mockito mocked method is returning NULL
A working example of your requirement could be:
@RunWith(MockitoJUnitRunner.class)
public class MemberTest {
@InjectMocks
private Member member;
@Mock
private MemberDao memberDao;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void createId() throws Exception {
MembersIdDto dto = new MembersIdDto();
dto.setId("967405286");
when(memberDao.findNext()).thenReturn(dto);
assertThat(member.createNewId()).isEqualTo("967405286");
}
}
…with the classes-under-test…
public class Member {
@Resource
MemberDao memberDao;
public String createNewId() {
return memberDao.findNext().getId();
}
}
…and…
public class MemberDao {
public MembersIdDto findNext() {
return null; // or whatever
}
}
…and…
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class MembersIdDto {
private String id;
}
By the way, I use the AssertJ assertion framework and with member.createNewId()
you have now a real call on production code.
Mocked method is returning null instead of expected object
When you partially mock static methods of a class, you need to explicitely state if real implementation should be called (check thenCallRealMethod
below).
If you don't that, any method you call would be treated as a method on a mock without specified behaviour, and thus return null.
On top of that:
- you use
EJBFacades
which was not posted in the question. I've rewritten the test in terms ofXYZClass
- your assertion will fail, as you return a subclass of the service.
package com.test.powermock.teststacitejb;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import javax.naming.InitialContext;
import static org.junit.Assert.assertTrue;
@RunWith(PowerMockRunner.class)
@PrepareForTest(XYZClass.class)
public class XYZClassTest {
private InitialContext ctx;
@Before
public void setUp() throws Exception {
PowerMockito.mockStatic(XYZClass.class);
ctx = Mockito.spy(new InitialContext());
PowerMockito.doReturn(ctx).when(XYZClass.class, "getCtx");
IMFTPManagerBean service1 = new IMFTPManagerBean();
Mockito.doReturn(service1).when(ctx).lookup(Mockito.eq("abc"));
PowerMockito.when(XYZClass.getIMFTPManagerFacade()).thenCallRealMethod();
}
@Test
public void testGetIMFTPManagerFacade() {
IMFTPManagerService service = XYZClass.getIMFTPManagerFacade();
assertTrue(service instanceof IMFTPManagerService);
}
}
Mocked object returns null
It's most likely returning null because your parameter definition in when
and the actual parametes differ. In your case it's very likely that your mocked entity
and the HttpEntity
you're creating in your code under test are neither the same nor equal. So you need to widen your expectations in the when
-definition. You should use Matchers in your definition and the could use isA(HttpEntity.class)
for your entity.
Mockito when()...then() methods not returning the expected mock object (returns null), what am I doing wrong?
Using @InjectMocks
seems to be wrong here.
After removing that annotation and instantiating the class in the test itself I can get things working.
This also meant I no longer needed attributes and internal classes to be static.
Related Topics
How to Handle JPA Unique Constraint Violations
How to Test Code Dependent on Environment Variables Using Junit
Mockito Mock Objects Returns Null
Maven Build Cannot Find Symbol When Accessing Project Lombok Annotated Methods,
Regex to Match a String Not Starting or Ending With a Pattern
How to Pass a List and a Separate String Using @Requestbody in Springboot
Set Current Timezone to @Jsonformat Timezone Value
Cannot Connect to Localhost API from Android App
Largest and Smallest Integer - Exercise from Deitel'S Java Book
How to Check Type of Variable in Java
Java Classes to Generate the Given Json String
Better Way to Detect If a String Contains Multiple Words
In Java, How to Determine If a Char Array Contains a Particular Character
In Firebase After Uploading Image How to Get Url
How to Valid @Requestheader in Spring Boot
Error: Incompatible Types: List<Integer> Cannot Be Converted to Arraylist<Integer>