使用JUnit为局部变量模拟数据

hrysbysz  于 2023-04-12  发布在  其他
关注(0)|答案(2)|浏览(176)

需要帮助我对JUnit很陌生,我想为下面的方法创建一个JUnit测试用例,我想为下面的方法中定义为本地的webClient传递值。所以我需要为webClient传递值。请指导我如何为webClient存根值?

@Autowired
@Qualifier("oauthproviders")
Map<String, WebClient> webClientList;

public static Map<String, String> mapClientAccounts = new HashMap<>();
public void callRemoteListenerService(final String uuid, final String userName,
        final boolean mode, File file) throws FileNotFoundException {
    WebClient webClient = webClientList.get(mapClientAccounts.get(userName));
        
    logger.info("The list in webclients are: " + webClientList.keySet().toString());
    
    // Some other code...
}
bfrts1fy

bfrts1fy1#

第一:“下面的方法”,绝不“下面的方法”。
简短回答:
1.创建一个“webClientList”的模拟。
1.创建一个“mapClientAccounts”的模拟。
1.为“mapClientAccouns.get(userName)”调用创建一个模拟帐户以返回。
1.为“webClientList.get”调用创建一个mock WebClient以返回。

  1. stub调用webClientList.get以返回mockWebClient;
  2. stub mapClientAccouns.get(userName)调用以返回mockAccount
    示例代码(基于一些假设):
@ExtendWith(MockitoExtension.class)
public class TestYourClass
{
    private static final String VALUE_USERNAME = "VALUE_USERNAME";

    @InjectMocks
    private YourClass classToTest;

    private UUID liveUUID;
    
    @Mock
    private ClientAccount mockClientAccount;

    @Mock
    private Map<String, ClientAccount> mockClientAccountMap;

    @Mock
    private File mockFile;
    
    @Mock
    private Map<ClientAccount, WebClient> mockWebClientMap;

    @Mock
    private WebClient mockWebClient;

    @BeforeEach
    void beforeEach()
    {
        liveUUID = UUID.randomUUID();
    }

    @Test
    void callRemoteListenerService_blahblahblah()
    {
        doReturn(mockClientAccount).when(mockClientAccountMap).get(VALUE_USERNAME);
        doReturn(mockWebClient).when(mockWebClientMap).get(mockClientAccount);
        
        classToTest.callRemoteListenerService(liveUUID, VALUE_USERNAME, true, mockFile);
        
        ... do the rest.
    }
}
oyt4ldly

oyt4ldly2#

假设包含此方法和2个map的类名为“TestedService”,您可以尝试以下操作:

@Test
void test() {
    // given
    var mockedWebClient = mock(WebClient.class);
    var webClientList = Map.of("test_web_client", mockedWebClient);
    TestedService.mapClientAccounts(Map.of("test_username", "test_web_client"));
    var service = new TestedService(webClientList);
    
    //when
    service.callRemoteListenerService("test_uuid", "test_username");
    
    //then
    ...
}

请注意,mapClientAccounts是静态的,这将使测试变得更加困难。在这种情况下,我们很幸运,因为它是公共的,我们可以修改它以进行测试。尽管如此,如果可能的话,最好将其作为非静态参数使用,并将其作为构造函数参数传递。

相关问题