Junit In Java

1. Junit test in java ?
Answer:- We should know as mention below before to start Junit test in java. 

what is assert in java ?

Java 8
JUnit 4.12



  • @Test
  • @BeforeClass
  • @Before
  • @Test
  • @Test(expected = ArithmeticException.class)
  • @Test(timeout = 2000) : Use to define execution time. method should be complete execution on or before this timeout.
  • @After
  • @AfterClass
  • @Rule : 
  • @ClassRule :
  • @RunWith(Categories.class)
  • @Categories.IncludeCategory
  • @Suite.SuiteClasses
  • Group Test : 
  • @RunWith(Suite.class)
  • @RunWith(Categories.class)
  • @Category(SlowTests.class)
  • @FixOrderMethod
  • setUp() method
  • tearDown( ) method
  • RunListener : refer - RunListener
2. How to write Junit test case for static class or static methods in java ? How to mock static class or static member for testing.
Answer :- We can use PowerMock to test static class or static methods for testing.

3. How to write Junit test case for void methods in java ?

4. How to write Junit test case for Singleton class ? 
Answer :- Junit test case for Singleton class.

5. Unit Testing Rest Services with Spring Boot and Junit ?

6. How to write Junit test for spring testing ?
Spring framework reference - Junit Testing 

Q- @mock vs @injectmocks vs @mockbean vs @Spy

Mockito.mock(): The Mockito.mock() method allows us to create a mock object of a class or an interface.
Mockito’s @Mock Annotation: (org.mockito.Mock): This annotation is a shorthand for the Mockito.mock() method.
We can do this either by using the MockitoJUnitRunner to run the test i.e. @RunWith(MockitoJUnitRunner.class)  or calling the MockitoAnnotations.initMocks() method explicitly.

// Using Mockito.mock()
UserRepository mockRepository = Mockito.mock(UserRepository.class);
// Using @Mock
UserRepository mockRepository;

long userCount = mockRepository.count();

Spring Boot’s @MockBean Annotation:  This is used in spring framework. (org.springframework.boot.test.mock.mockito.MockBean), We can use the @MockBean to mock objects to the Spring application context. To use this annotation, we have to use SpringRunner to run the test i.e. @RunWith(SpringRunner.class)

Mockito.spy() Or @Spy: Mockito.spy() Or @Spy is a way to creating partial mocks object that means we want to use default behavior of the method without stubbing that. but if required we can define some custom behavior for its methods (via doReturn(…)).
The reason is that, it guarantees real methods are called against correctly constructed object because you're responsible for constructing the object passed to spy() method.
Spy can be useful when you want to create unit tests for legacy code.

Note:- if we stub a spy method.it will result the same as the mock object.

    Related Tutorial

    No comments:

    Post a Comment