模拟的存储库在服务中变为null

huangapple go评论71阅读模式
英文:

Mocked repository becoming null in service

问题

@Service("HRfeedService")
public class HRfeedService {
    @Autowired
    private HRfeedRepository hRfeedRepository;

    public boolean getBBHRFeedDetails(String sid) {
        List<HRfeed> list = hRfeedRepository.getHRfeedDetailsBySID(sid);
       
        if(list.size() > 0) {
            bbHrStatus = true;
        }

        return bbHrStatus;
    }
}
@Repository
public interface HRfeedRepository extends JpaRepository<HRfeed, HRfeedID> {
    @Query(value = "select * from HRFEED_Details hr where hr.sid= ?1 and ACTIVE_FLAG='1'", nativeQuery = true)
    public List<HRfeed> getHRfeedDetailsBySID(String sid);
}
@RunWith(PowerMockRunner.class)  // Use PowerMockRunner for static mocking
@PrepareForTest({HRfeedService.class})  // Prepare the class for mocking
public class TestHRfeedService2 {

    String sid = "A123456";
    
    @InjectMocks
    private HRfeedService hRfeedService;
    
    @Mock
    HRfeedRepository hRfeedRepository;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        hRfeedService = new HRfeedService();
    }

    @Test
    public void testGetBBHRFeedDetails() throws Exception {
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yy hh.mm.ss.SSSSSSSSS a");
        ArrayList<HRfeed> list = new ArrayList<>();
        
        HRfeed hRfeed = new HRfeed();
        hRfeed.setSid("A123456");
        hRfeed.setEmail("test@gmail.com");
        hRfeed.setACTIVE_FLAG('1');
        Timestamp timestamp = new Timestamp(dateFormat.parse("19-NOV-19 04.43.17.740000000 PM").getTime());
        hRfeed.setEFF_UNTIL_DATE(timestamp);
        hRfeed.setEFF_ASOF_DATE(timestamp);
        
        list.add(hRfeed);
        
        PowerMockito.whenNew(HRfeedService.class).withNoArguments().thenReturn(hRfeedService);  // Mock the constructor
        
        PowerMockito.when(hRfeedRepository.getHRfeedDetailsBySID(Mockito.anyString())).thenReturn(list);
        
        boolean result = hRfeedService.getBBHRFeedDetails(sid);
        assertEquals(result, true);
    }
}

You can use the PowerMockRunner and the PrepareForTest annotation to mock static methods or constructor calls in your test case. The code above demonstrates how to mock the constructor of the HRfeedService class using PowerMockito and then proceed with your usual mocking of repository behavior. This should help you mock your service successfully.

英文:

Hi I have a springboot application which has a service in which repository is mocked in test case but it is not getting mocked.Below is my code sample

@Service(&quot;HRfeedService&quot;)
public class HRfeedService {
@Autowired
private HRfeedRepository hRfeedRepository;
public boolean getBBHRFeedDetails(String sid){
List&lt;HRfeed&gt; list = hRfeedRepository.getHRfeedDetailsBySID(sid);
if(list.size()&gt;0){
bbHrStatus = true;
}
return bbHrStatus;
}
}

My repository class here:

@Repository
public interface HRfeedRepository extends JpaRepository&lt;HRfeed,HRfeedID&gt; {
@Query(value = &quot;select * from HRFEED_Details hr where hr.sid= ?1 and ACTIVE_FLAG=&#39;1&#39;&quot;,nativeQuery = true)
public List&lt;HRfeed&gt; getHRfeedDetailsBySID(String sid);
}

Mytest clas is here:

@RunWith(SpringJUnit4ClassRunner.class)
public class TestHRfeedService2 {
String sid=&quot;A123456&quot;;
@InjectMocks
private HRfeedService hRfeedService;
@Mock
HRfeedRepository hRfeedRepository;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
hRfeedService = new HRfeedService();
}
@Test
public void testGetBBHRFeedDetails() throws Exception
{
SimpleDateFormat dateFormat = new SimpleDateFormat(&quot;dd-MMM-yy hh.mm.ss.SSSSSSSSS a&quot;);
ArrayList&lt;HRfeed&gt; list = new ArrayList&lt;&gt;();
HRfeed hRfeed = new HRfeed();
hRfeed.setSid(&quot;A123456&quot;);
hRfeed.setEmail(&quot;test@gmail.com&quot;);
hRfeed.setACTIVE_FLAG(&#39;1&#39;);
Timestamp timestamp = new Timestamp(dateFormat.parse(&quot;19-NOV-19 04.43.17.740000000 PM&quot;).getTime());
hRfeed.setEFF_UNTIL_DATE(timestamp);
hRfeed.setEFF_ASOF_DATE(timestamp);
list.add(hRfeed);
Mockito.when(hRfeedRepository.getHRfeedDetailsBySID(anyString())).thenReturn(list);
boolean result = hRfeedService.getBBHRFeedDetails(sid);
assertEquals(result,true);
}
}

I would like to use powermockrunner if possible otherwise also fine.When I am mocking repository it is not getting mocked instead in service it is taken as null.

Please let me know how to mock my service.

答案1

得分: 2

以下是翻译好的部分:

我觉得你似乎忘记在测试中将存储库注入到服务中了。

在“生产”中,Spring会为您处理这个问题,但在测试中,您正在使用Mockito。您有几个选择,其中一个是使用Spring的测试基础设施,另一个是在服务上提供一个带有存储库实例的构造函数。

类似于以下内容:

@Service("HRfeedService")
public class HRfeedService {

   ... 类的其余部分

   @Autowired
   private HRfeedRepository hRfeedRepository;

   public HRfeedService(HRfeedRepository hRfeedRepository) {
      this.hRfeedRepository = hRfeedRepository;
   }

   ... 类的其余部分
}

在测试类的 @Before 方法中,可以这样写:

   hRfeedService = new HRfeedService(mockRepository);

其中 mockRepository 是您使用Mockito设置的存储库模拟对象。

个人而言,我更倾向于使用构造函数进行自动装配,而不是字段,这使我可以将字段声明为final,并且通常我可以省略 @Autowired,因为Spring可以自己解决这个问题。

英文:

It looks to me like you have forgotten to inject the repository into the service in the test.

In "production" Spring will handle this for you, but in the test you are using Mockito. You have a couple of choices, one is to use Spring's test infrastructure, the other is to provide a constructor on the service that takes an instance of the Repository.

Something like:

@Service(&quot;HRfeedService&quot;)
public class HRfeedService {
... rest of class
@Autowired
private HRfeedRepository hRfeedRepository;
public HRfeedService(HRfeedRepository hRfeedRepository) {
this.hRfeedRepository = hRfeedRepository;
}
... rest of class
}

In the @Before of the test class something like:

   hRfeedService = new HRfeedService(mockRepository);

where mockRepository if the repository mock you have set up with Mockito.

Personally I lean towards using constructors for autowiring rather than fields, this allows me to make my fields final, and often I can omit the @Autowired as Spring can figure it out.

huangapple
  • 本文由 发表于 2020年9月17日 15:28:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/63933206.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定