是否可以使用预定义的ArrayList作为DB模拟身份验证?

发布于 2025-01-29 19:40:50 字数 2500 浏览 2 评论 0原文

我正在学习模拟,我想知道我是否可以使用类似的代码:

Mockito.when(service.authenticateUser(test)).thenReturn(any());

验证身份验证的成功。

service.authenticateuser(用户用户):

@Override
public Player authenticateUser(User login) throws AuthenticationException {
    Player find = new Player();

    for (Player player : initializedPlayers) {
            if (login.getEmail().equals(player.getEmail()) && login.getPassword().equals(player.getPassword())) {

            loggedPlayer = player;
            return player;
            }
    }
    throw new AuthenticationException("Incorrect email and/or password");
}

如您所见,登录方法返回player,但是是否有一种可能的方法告诉M​​ockito我只想得到一些东西回来,如果有效?因此,我将能够测试身份验证是否成功,例如:

Mockito.when(service.authenticateUser(test)).thenReturn(any(Player.class));
    assertNotNull(service.authenticateUser(test));

^此方法当前不起作用,它给出了对存根的失败测试。

编辑:我尝试以两种不同的方式处理此操作:

@Test
public void testFailAuthWithMockedService(){
    DefaultSportsBettingService service = mock(DefaultSportsBettingService.class);
    User test = new User("test","test");
    Mockito.when(service.authenticateUser(test)).thenReturn(any(Player.class));
    assertNotNull(service.authenticateUser(test));
}
@Test
public void testSuccessfulAuthWithMockedService(){
    DefaultSportsBettingService service = mock(DefaultSportsBettingService.class);
    User test = new User("validName","validPassword");
    Mockito.when(service.authenticateUser(test)).thenReturn(any());
    assertNotNull(service.authenticateUser(test));
}

这些代码符合,但我不确定它们是否真的很好。

附加信息: 从一开始我的主体中调用此方法:

 @Override
public Player authenticateUser(User login) throws AuthenticationException {
    Player find = new Player();

    for (Player player : initializedPlayers) {
            if (login.getEmail().equals(player.getEmail()) && login.getPassword().equals(player.getPassword())) {

            loggedPlayer = player;
            return player;
            }
    }
    throw new AuthenticationException("Incorrect email and/or password");
}

main():(使用身份验证的那部分部分)

 while(true) {
        try {
            dsbs.authenticateUser(view.readCredentials());
            if(dsbs.getLoggedPlayer() != null){
                break;
            }


        } catch (AuthenticationException ae) {
            ae.printStackTrace();
        }
    }

I'm learning mock and I wonder if I could use a code similar as this:

Mockito.when(service.authenticateUser(test)).thenReturn(any());

to validate the success of authentication.

service.AuthenticateUser(User user):

@Override
public Player authenticateUser(User login) throws AuthenticationException {
    Player find = new Player();

    for (Player player : initializedPlayers) {
            if (login.getEmail().equals(player.getEmail()) && login.getPassword().equals(player.getPassword())) {

            loggedPlayer = player;
            return player;
            }
    }
    throw new AuthenticationException("Incorrect email and/or password");
}

As you can see, the login method returns a Player, but is there a possible way to tell Mockito that I only want to get something back, if its valid? So I would be able to test wheter the authentication was succesful or not, e.g.:

Mockito.when(service.authenticateUser(test)).thenReturn(any(Player.class));
    assertNotNull(service.authenticateUser(test));

^this method currently not working, it gives failed test on stub.

EDIT: I tried approaching this in two different way:

@Test
public void testFailAuthWithMockedService(){
    DefaultSportsBettingService service = mock(DefaultSportsBettingService.class);
    User test = new User("test","test");
    Mockito.when(service.authenticateUser(test)).thenReturn(any(Player.class));
    assertNotNull(service.authenticateUser(test));
}
@Test
public void testSuccessfulAuthWithMockedService(){
    DefaultSportsBettingService service = mock(DefaultSportsBettingService.class);
    User test = new User("validName","validPassword");
    Mockito.when(service.authenticateUser(test)).thenReturn(any());
    assertNotNull(service.authenticateUser(test));
}

These codes comply, but I'm not sure if they are truely good.

Additional information:
This method is called in my main at the very beginning:

 @Override
public Player authenticateUser(User login) throws AuthenticationException {
    Player find = new Player();

    for (Player player : initializedPlayers) {
            if (login.getEmail().equals(player.getEmail()) && login.getPassword().equals(player.getPassword())) {

            loggedPlayer = player;
            return player;
            }
    }
    throw new AuthenticationException("Incorrect email and/or password");
}

The main(): (that part of the main which uses the authentication)

 while(true) {
        try {
            dsbs.authenticateUser(view.readCredentials());
            if(dsbs.getLoggedPlayer() != null){
                break;
            }


        } catch (AuthenticationException ae) {
            ae.printStackTrace();
        }
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

爱冒险 2025-02-05 19:40:50

您不能在thatreturn语句中使用任何(...),这就是错误的来源。

此代码应该有效:

Mockito.when(service.authenticateUser(test)).thenReturn(new Player(...));
assertNotNull(service.authenticateUser(test));

现在,如果您要根据登录值进行模拟结果,则可以使用wher()部分中的参数匹配者:

Mockito.when(service.authenticateUser(any(User.class))
  .thenThrow(AuthenticationException.class);
Mockito.when(service.authenticateUser(argThat(login -> list.contains(login))
  .thenReturn(new Player(...));

assertNotNull(service.authenticateUser(test));

此处的顺序很重要:莫科托(Mockito)将尝试以Stubs的反向顺序匹配您的参数,因此,这里将首先检查登录是否在给定列表中,如果该存根失败,它将落后于第一个存根,这将为其他任何东西抛出AuthenticationException。

如果您希望返回的播放器取决于登录用户,则可以使用.thenanswer()而不是.thenreturn()。参见 oighito:doanswer vs theReturn

You can't use any(...) in the thenReturn statement, that's where the error comes from.

This code should work:

Mockito.when(service.authenticateUser(test)).thenReturn(new Player(...));
assertNotNull(service.authenticateUser(test));

Now if you want to stub different results depending on the value of the login, you can use argumentMatchers in the when() part:

Mockito.when(service.authenticateUser(any(User.class))
  .thenThrow(AuthenticationException.class);
Mockito.when(service.authenticateUser(argThat(login -> list.contains(login))
  .thenReturn(new Player(...));

assertNotNull(service.authenticateUser(test));

Here the order is important: Mockito will try to match your argument in reverse order of stubs, so here it will first check if the login is in the given list, and if that stub fails, it will fall back to the first stub, which will throw an AuthenticationException for anything else.

If you want the returned Player to be dependent on the login User, you can use .thenAnswer() instead of .thenReturn(). See Mockito : doAnswer Vs thenReturn

黯然 2025-02-05 19:40:50
Mockito.when(service.authenticateUser(test)).thenReturn(any(Player.class));
assertNotNull(service.authenticateUser(test));

通过模拟service.authenticateuser(test)的返回值,您正在测试Mockito,而不是您自己的代码。

是否有一种可能的方法告诉M​​ockito,如果有效,我只想收回一些东西?因此,我可以测试身份验证是否成功

使用Mockito。相反,您需要创建initializedPlayers的列表,并使其可用于AuthenticateUser()函数。理想情况下,您只需将此列表传递到Service对象的构造函数时,您可以在测试中创建它。如果不是,那么您必须以服务在需要时获得的方式创建玩家。

同样,您可以创建一个测试来验证authenticateUser()投掷AuthenticationException当给定用户不在玩家列表中时。

Mockito.when(service.authenticateUser(test)).thenReturn(any(Player.class));
assertNotNull(service.authenticateUser(test));

By mocking the return value of service.authenticateUser(test), you are testing Mockito, not your own code.

is there a possible way to tell Mockito that I only want to get something back, if its valid? So I would be able to test wheter the authentication was succesful or not

Don't use Mockito for this. Instead, you need to create a list of initializedPlayers and make it available to the authenticateUser() function. Ideally, you can just pass this list to the service object's constructor when you create it in your test. If not, then you have to create the players in a way that the service will get them when it needs to.

Similarly, you can create a test to verify that authenticateUser () throws AuthenticationException when the given user is not in the list of players.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文