Spring JUnit: How to Mock autowired component in autowired component
You can provide a new testContext.xml in which the @Autowired
bean you define is of the type you need for your test.
Mock a method inside autowired component using Spring, JUnit and Mockito
You can just use @MockBean
in your test like this (if @RunWith(SpringRunner.class)
)
@MockBean private MeterManagementService meterManagementService
It will be mocked and injected.
If you are not using or you cannot use SpringRunner
use constructor/setter to set your dependencies - there you will be able to provide mocked instances and use it at will.
How to mock object for @Autowired in junit 5 unit test?
I added @SpringBootTest at the begining of my class. It worked. Make sure your import are correct for junit 5. here my code,
package com.inslab.reader;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mock.web.MockMultipartFile;
import com.google.zxing.Result;
import com.inslab.reader.ImageProcessor;
import com.inslab.reader.IReader;
@SpringBootTest
class BarcodeReaderServiceTest {
@InjectMocks
BarcodeReaderService barcodeReaderService;
@Mock
ImageProcessor imageProcessor;
@BeforeEach //instead of @Before have to use @BeforeEach in junit5
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
void testDummy() {
Mockito.when(imageProcessor.dummy("name")).thenReturn("name");
String name = barcodeReaderService.dummy("name");
Assertions.assertEquals("name", name);
}
}
Mockito - Mock Autowired Service
You are not actually calling the Controller method in your test, that is why it is complaining that the call to dbCacheService.refreshCache()
never happens. Try the following:
@ExtendWith(MockitoExtension.class)
class SmsControllerTest {
@Mock
private DbCacheService dbCacheService;
@InjectMocks
private AppController appController;
@BeforeMethod
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
void refreshCache() {
appController.refreshCache();
Mockito.verify(dbCacheService, Mockito.times(1)).refreshCache();
}
}
Although this might work, this is not the right way to test Controllers. You should test them by actually making an HTTP request and not a method call. In order to do this, you need a slice test with @WebMvcTest
:
- https://www.baeldung.com/spring-boot-testing#unit-testing-with-webmvctest
- https://rieckpil.de/spring-boot-test-slices-overview-and-usage/
Something in the line of:
@RunWith(SpringRunner.class)
@WebMvcTest(AppController.class)
public class AppControllerTest {
@Autowired
private MockMvc mvc;
@MockBean
private DbCacheService dbCacheService;
@Test
public void refreshCache() {
mvc.perform(get("/refresh")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
Mockito.verify(dbCacheService, Mockito.times(1)).refreshCache();
}
}
Related Topics
@Responsebody , Responseentity Spring Return Object as Json
Spring Rest - Create Zip File and Send It to the Client
Jpa:How to Convert a Native Query Result Set to Pojo Class Collection
Spring Boot - Post Method Not Allowed, But Get Works
How to Mock a Generic Parameter for a Unit Test in Java
Java.Lang.Noclassdeffounderror: Org/Json/Simple/Parser/Parseexception With Eclipse and Spring
Utf-8 Encoding of Application.Properties Attributes in Spring-Boot
Javax.Xml.Bind.Unmarshalexception: Unexpected Element (Uri:"", Local:"Group")
Keycloak - Create Realms/Users/Groups Programmatically
Eclipse Problems View Not Showing Errors Anymore
How to Convert Linkedhashmap to Custom Java Object
How to Store a String Longer Than 4000 Characters in an Oracle Database Using Java/Jdbc
Serialize a Double to 2 Decimal Places Using Jackson
Check If One List Contains Element from the Other
How to View Apache Parquet File in Windows
How to Make Multiple Line String to Single Line String
Spring Boot Rest API Returns 404
How to Query Using an Enum Parameter Mapped as Ordinal Using JPA and Hibernate