Easymock: порядок получений имеет значение?

Я подумал, что позволю вам разобраться, как сделать это самостоятельно, но я решил другие ваши проблемы и оставил комментарии, где я что-то изменил. Надеюсь, это поможет

//declared variables here. global variables must be declared static when accessed in a static method (ex: user_input())
static int y_;
static int m_;
static int b_;
static int x_;

public static void main(String[] args) {
    // Creates scanner for input of menu Def as menu selector
    Scanner user_Selection = new Scanner(System.in);

    System.out.println("Enter 1 if you would like to solve for Y?");
    System.out.println("Enter 2 if you would like to solve for M?");
    System.out.println("Enter 3 if you would like to solve for B?");
    System.out.println("Enter 4 to Quit");

    //Converts user input to an integer
    int selection = user_Selection.nextInt();

    //call user_input()
    user_input(selection);


}

public static void user_input(int selection) {

    Scanner user_Selection = new Scanner(System.in);
    int userAnswer;
    int y_intercept = (int) (Math.floor(Math.random() * 201) - 100);
    int slope = (int) Math.floor(Math.random() * 201) - 100;
    int point_of_line_cross = (int) Math.floor(Math.random() * 201) - 100;
    int independent_variable = (int) Math.floor(Math.random() * 201) - 100;

    y_ = point_of_line_cross;
    m_ = slope;
    b_ = y_intercept;
    x_ = independent_variable;


    //Tests what user input was, with expected output
    if (selection == (1)) {
        System.out.println("You chose to solve for Y: ");
        System.out.println("Y = " + slope + "(" + independent_variable + ")" + " + " + y_intercept);
        System.out.println("Input your answer: ");
        userAnswer = user_Selection.nextInt();
        /*After user enters answer we test the answer by calling test_input
         * */
       test_input(userAnswer);
    } else if (selection == (2)) {
        System.out.println("You chose to solve for M: ");
        System.out.println("M = " + "(" + point_of_line_cross + " - " + y_intercept + ")" + " / " + independent_variable);
        System.out.println("Input your answer: ");
        userAnswer = user_Selection.nextInt();
        /*After user enters answer we test the answer by calling test_input
         * */
        test_input(userAnswer);
    } else if (selection == (3)) {
        System.out.println("You chose to solve for B: ");
        System.out.println("B = " + point_of_line_cross + " - " + slope + "(" + independent_variable + ")");
        System.out.println("Input your answer: ");
        userAnswer = user_Selection.nextInt();
        /*After user enters answer we test the answer by calling test_input
         * */
        test_input(userAnswer);
    } else if (selection == (4)) {
        System.out.println("You chose to quit the program. ");
    }
}

// you forgot to include return type ex: void, int, String, double, float, etc
public static void test_input(int entered_answer) {
    //Solves the problem in order to compare to User input
    int answer_y = ((m_) * (x_)) + (b_);
    int answer_m = (y_) - ((b_) / (x_));
    int answer_b = (y_) - ((m_) * (x_));

    //Problem solver defined
    int answer = entered_answer;

    //Creates loop for program
    int counter = 0;
    int correct = 0;
    boolean answers_correct = false;

    while (!answers_correct && correct < 3) {
        if (answer == answer_y) {
            counter++;
            correct++;
            System.out.println("You answered correctly");
            return;
        } else if (counter >= 3 && correct < 3) {
            System.out.println("You've been missing the questions lately, let me help! ");
        } else {
            System.out.println("Try again");
            counter++;
            correct = 0;
            break;
        }
    }

}

`

public static void user_input(int point_of_line_cross, int slope, int y_intercept, int independent_variable)

Если вы дадите параметры метода, то при вызове метода вам придется самостоятельно вводить значения в параметр. Я не думаю, что это то, что вы намеревались, потому что вы определили, что вы хотели, чтобы значения этих параметров были здесь:

y_intercept = (int) (Math.floor(Math.random() * 201) - 100);
slope = (int) Math.floor(Math.random() * 201) - 100;
point_of_line_cross = (int) Math.floor(Math.random() * 201) - 100;
independent_variable = (int) Math.floor(Math.random() * 201) - 100;

В вашем методе test_input () вы написали:

Scanner answer_input = new Scanner(System.in);
int answer = answer_input.nextInt();

.nextInt () заставит программу остановиться и ждать ввода пользователя, поэтому вы не захотите использовать его, пока не будете готовы получить ввод.

Я не очень много знаю о ключевом слове var в java, но вместо того, чтобы использовать var, я решил, что нужно просто объявить тип переменной так:

var counter = 0;

так:

[ 115]

и чтобы лучше понять, как работают методы, я рекомендую эти два видео: Введение в java-методы Параметры метода Java и возвращаемые типы

Для подробное объяснение основ java в целом, тогда я рекомендую весь этот плейлист Java Beginner Programming

6
задан matt b 19 February 2009 в 16:38
поделиться

5 ответов

Я получил ответ на ошибке, которую я отправил сайту SourceForge Easymock, и разработчик подтвердил, что это - действительно ошибка с этой версией Easymock.

Это - действительно ошибка. Получение сделано, даже если оно было уже сделано. Текущее обходное решение должно реализовать Ваш собственный объект получения и переопределить setValue, чтобы сделать это:

@Override
public void setValue(T value) {
  if(!hasCaptured()) {
    super.setValue(value);
  }
}
4
ответ дан 17 December 2019 в 07:09
поделиться

Я играл вокруг с Вашим тестом и не мог решить. Однако я расширил Класс Получения, чтобы видеть, были ли значения установлены в другом порядке (я был подозрителен, что EasyMock внутренне использовал хеш с ключом, сгенерированным из методов и параметров), я был неправ, что методы установлены в правильном порядке. Но существует что-то действительно странное продолжение.. Кажется, что алгоритм делает некоторый добрый шаблон присвоения.. Хорошо позвольте мне показать код и странный вывод.... BTW изменения от насмешки, niceMock и strictMock не сделал anydifference..

class MyCapture extends Capture<String> {

    private String id;

    public MyCapture(String id) {
        super();
        System.out.printf("Constructor %s expecting %s\n", id, this.getClass().getName());
        this.id = id;
    }

    private static final long serialVersionUID = 1540983654657997692L;

    @Override
    public void setValue(String value) {
        System.out.printf("setting value %s expecting %s \n", value, id);
        super.setValue(value);
    }

    @Override
    public String getValue() {
        System.out
                .printf("getting value %s expecting %s \n", super.getValue(), id);
        return super.getValue();
    }
}


public void testCapture() {

    // create the mock, wire it up
    Processor mockProcessor = createStrictMock(Processor.class);
    Component component = new Component(mockProcessor);

    // we're going to call the process method four times
    // with different arguments, and we want to capture
    // the value passed to the mock so we can assert against it later
    Capture<String> cap1 = new MyCapture("A");
    Capture<String> cap2 = new MyCapture("B");
    Capture<String> cap3 = new MyCapture("C");
    Capture<String> cap4 = new MyCapture("D");

    mockProcessor.process(and(isA(String.class), capture(cap1)));
    mockProcessor.process(and(isA(String.class), capture(cap2)));
    mockProcessor.process(and(isA(String.class), capture(cap3)));
    mockProcessor.process(and(isA(String.class), capture(cap4)));
    replay(mockProcessor);

    component.doSomething();

    // check what values were passed to the mock
    assertEquals("A", cap1.getValue());
    assertEquals("B", cap2.getValue());
    assertEquals("C", cap3.getValue());
    assertEquals("D", cap4.getValue());

    verify(mockProcessor);
}

}

*И это - вывод *

Constructor A expecting com.comp.core.dao.impl.CaptureTest$MyCapture
    Constructor B expecting com.comp.core.dao.impl.CaptureTest$MyCapture
    Constructor C expecting com.comp.core.dao.impl.CaptureTest$MyCapture
    Constructor D expecting com.comp.core.dao.impl.CaptureTest$MyCapture
    calling process A 
    setting value A expecting A 
    calling process B 
    setting value B expecting A <<Setting the wrong guy
    setting value B expecting A <<Setting the wrong guy
    setting value B expecting B <<Ops this is the right one..stop
    calling process C 
    setting value C expecting B <<Setting the wrong guy
    setting value C expecting B <<Setting the wrong guy
    setting value C expecting C <<Setting the wrong guy
    calling process D 
    setting value D expecting C <<Setting the wrong guy
    setting value D expecting C <<Setting the wrong guy
    setting value D expecting D <<Ops this is the right one..stop
    getting value B expecting A 

Извините я не могу помочь Вам больше. Это могла бы быть действительно ошибка в легкой насмешке.

1
ответ дан 17 December 2019 в 07:09
поделиться

Можно также попытаться использовать EasyMock.createNiceMock (...) вместо EasyMock.createStrictMock (...) или EasyMock.createMock (...).

Хотя, я соглашаюсь, что это больше походит на ошибку с createMock.

0
ответ дан 17 December 2019 в 07:09
поделиться

Вместо того, чтобы назвать EasyMock.createStrictMock (...) просто называют EasyMock.createMock (...). Должен решить Ваши проблемы.

-1
ответ дан 17 December 2019 в 07:09
поделиться

Думаю, эта проблема больше подходит для тестирования на основе состояний. С JMockit вы можете решить эту проблему следующим образом:

import mockit.*;
import static mockit.Mockit.*;
import mockit.integration.junit3.*;

public class CaptureTest extends JMockitTestCase
{
   interface Processor { void process(String x); }

   class Component
   {
      private final Processor processor;
      private final String[] s = {"one", "two", "three", "four"};

      Component(Processor processor) { this.processor = processor; }

      public void doSomething()
      {
         for (String value : s) {
            processor.process(value);
         }
      }
   }

   @MockClass(realClass = Processor.class)
   static class MockProcessor
   {
      private final String[] expectedValues;
      private int i;

      MockProcessor(String... expectedValues) { this.expectedValues = expectedValues; }

      @Mock
      void process(String x)
      {
         assertEquals(expectedValues[i++], x);
      }
   }

   public void testCapture()
   {
      Processor mockProcessor = setUpMock(new MockProcessor("one", "two", "three", "four"));
      Component component = new Component(mockProcessor);

      component.doSomething();
   }
}
0
ответ дан 17 December 2019 в 07:09
поделиться
Другие вопросы по тегам:

Похожие вопросы: