Autofixture, expected behavior? - autofixture

Having a test similar to this:
public class myClass
{
public int speed100index = 0;
private List<int> values = new List<int> { 200 };
public int Speed100
{
get
{
return values[speed100index];
}
}
}
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var fixture = new Fixture();
var sut = fixture.Create<myClass>();
Assert.AreEqual(sut.Speed100, 200);
}
}
Would have expected this to work, but I can see why it's not. But how do I argue, that this is not a problem with AutoFixture, but a problem with the code?

AutoFixture is giving you feedback about the design of your class. The feedback is, you should follow a more object-oriented design for this class.
Protect your private state, to prevent your class from entering an inconsistent state.
You need to make the speed100index field, private, to ensure it remains consistent with the values List.

Here is what I see if I run debugger on your test:
Autofixture assigns a random number to speed100index field because it is public, and in your array there is nothing at point 53 (from my screenshot)
If you set speed100index to be private, Autofixture will not re-assign the number and your test will pass.

Related

Index was outside the bounds of the array. // Array with AudioSource

I'm learning to code along with unity for the past 1.5month and I cannot get this problem resolved. I've tried looking it up several times and cannot get the answer that I need. I know it probably be a simple fix for everyone but for me - its not... i'm not good with Arrays.
I'm trying to make a script that going to handle my sounds but I keep getting this error. Here's the script;
public AudioSource[] mySounds;
public AudioSource fire;
public AudioSource reload;
public AudioSource zombieDeath;
void Start()
{
mySounds = GetComponents<AudioSource>();
fire = mySounds[0];
reload = mySounds[1]; // <---- line 22.
zombieDeath = mySounds[2];
}
public void PlayFire()
{
fire.Play();
}
public void PlayReload()
{
reload.Play();
}
public void PlayZombieDeath()
{
zombieDeath.Play();
}
And I keep getting the error in unity on line 22. I could use some help..

How do I call this list from another class in C#?

I am still new to the whole C# thing but I found this code posted from grovesNL about 5 years ago which I believe will work.
namespace DataAccessClass
{
public class FileReader
{
static void Main(string[] args)
{
List<DailyValues> values = File.ReadAllLines("C:\\Users\\Josh\\Sample.csv")
.Skip(1)
.Select(v => DailyValues.FromCsv(v))
.ToList();
}
}
public class DailyValues
{
DateTime Date;
decimal Open;
decimal High;
decimal Low;
decimal Close;
decimal Volume;
decimal AdjClose;
public static DailyValues FromCsv(string csvLine)
{
string[] values = csvLine.Split(',');
DailyValues dailyValues = new DailyValues();
dailyValues.Date = Convert.ToDateTime(values[0]);
dailyValues.Open = Convert.ToDecimal(values[1]);
dailyValues.High = Convert.ToDecimal(values[2]);
dailyValues.Low = Convert.ToDecimal(values[3]);
dailyValues.Close = Convert.ToDecimal(values[4]);
dailyValues.Volume = Convert.ToDecimal(values[5]);
dailyValues.AdjClose = Convert.ToDecimal(values[6]);
return dailyValues;
}
}
}
I am trying to read a csv file skipping the header and get it into a list that is accessible from another class. So my Architecture is DataAccessClass that has a class called FileReader and a class called Values. My task is to read this csv file into class FileReader and then to create an object list to hold it in the class Values. When I go to the Values class to call it I can't figure it out. This is how I am trying to call it. It is saying DailyValues.FromCsv(string) is a method that is not valid.
public List<string> GetList()
{
return DataAccessClass.DailyValues.FromCsv.dailyValues;
}
I want to be able to access this list further up the stack.
Your expression DataAccessClass.DailyValues.FromCsv.dailyValues is the culprit.
DataAccessClass.DailyValues.FromCsv is valid, and references the static method named FromCsv in the class DataAccessClass.DailyValues. But then going on by adding .dailyValues is incorrect. It is a method, nothing to peek into and extract stuff using ..
You could (if that was the intention) call the function, and directly work with the result:
DataAccessClass.DailyValues.FromCsv(some_csv_string) is an expression of type DailyValues. There you could then access - as an example - 'High' with:
DailyValues dv;
dv = DataAccessClass.DailyValues.FromCsv(some_csv_string);
dosomething(dv.High);
But for that to work, High would have to have the visibility of public.

Unity3D - how to use arrays with custom inspector code?

I seem to be stuck in a catch 22 situation with the OnInspectorGUI method of Unity's UnityEditor class. I want to name array elements in the inspector for easy editing, currently I'm using, as per the documentation:
public override void OnInspectorGUI()
{
J_Character charScript = (J_Character)target;
charScript.aBaseStats[0] = EditorGUILayout.FloatField("Base Health", charScript.aBaseStats[0]);
}
In my J_Character script I initialise the aBaseStats array like so:
public float[] aBaseStats = new float[35];
The problem is that whenever I try to do anything in the editor (and thus OnInspectorGUI is called) I get an index out of range error pointing to the line
charScript.aBaseStats[0] = EditorGUILayout.FloatField("Base Health", charScript.aBaseStats[0]);
I'm guessing this is because my array is initialized on game start while the editor code is running all the time while developing.
How can I get round this situation?
Many thanks.
You have to initialize aBaseStats in an function that runs only once.
The code below is BAD:
public float[] aBaseStats = new float[35];
void Start(){
}
The code below is GOOD:
public float[] aBaseStats;
void Start(){
aBaseStats = new float[35];
}
Initialize it in an Editor callback function that runs once.
EDIT:
I don't know a Start callback function that will run before the OnInspectorGUI function(). The hack below should work.
public float[] aBaseStats;
bool initialized = false;
public override void OnInspectorGUI()
{
if (!initialized)
{
initialized = true;
aBaseStats = new float[35];
}
J_Character charScript = (J_Character)target;
charScript.aBaseStats[0] = EditorGUILayout.FloatField("Base Health",aBaseStats[0]);
}
As an addition to the answer by Programmer I would like to point you to the following:
http://docs.unity3d.com/ScriptReference/ExecuteInEditMode.html
This seems to be exactly what you are looking for in terms of functionality. (it runs the method even when playmode is not active)
using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
public class ExampleClass : MonoBehaviour {
public Transform target;
void Update() {
if (target)
transform.LookAt(target);
}
}

what's the difference between object and primitive type when using matchers in EasyMock

//service to mock
public interface ServiceToMock {
public void operateDouble(Double dbValue);
public void operateCar(Car car);
}
//class under test
public class ClassUnderTest {
ServiceToMock service;
public void operateDouble(Double dbValue){
service.operateDouble(dbValue);
}
public void operateObject(Car car){
service.operateCar(car);
}
}
//unit test class
#RunWith(EasyMockRunner.class)
public class TestEasyMockMatcherUnderTest {
#TestSubject
private final ClassUnderTest easyMockMatcherUnderTest = new ClassUnderTest();
#Mock
private ServiceToMock mock;
#Test
public void testOperateCar() {
//record
mock.operateCar(EasyMock.anyObject(Car.class));
EasyMock.expectLastCall();
// replay
EasyMock.replay(mock);
//matcher here...
easyMockMatcherUnderTest.operateObject(EasyMock.anyObject(Car.class));
//easyMockMatcherUnderTest.operateObject(new Car());
// verify
EasyMock.verify(mock);
}
#Test
public void testOperateDouble() {
// record
mock.operateDouble(EasyMock.anyDouble());
EasyMock.expectLastCall();
// replay
EasyMock.replay(mock);
easyMockMatcherUnderTest.operateDouble(EasyMock.anyDouble());
// verify
EasyMock.verify(mock);
}
}
As the above code has shown, I intent to test two methods(operateDouble, operateObject). But things are kinda weird since everything runs fine in the operateDouble block while the compiler complaints an "Illegal state exception: 1 matchers expected, 2 recored." when runnig operateObject. And if commentting the method operateDouble out, the compaint goes away..So what is the difference between Double and my custom object Car, as the Double can also be considered as an object. And why does codes in operateObject runs well when commenting operateDouble method out?
EasyMock.anyDouble and EasyMock.anyObject are not meant to be used in replay mode. They are used to setup your expectations in record mode.
Use this in your first test (testOperateCar):
easyMockMatcherUnderTest.operateObject(new Car());
and something like this in your second (testOperateDouble):
easyMockMatcherUnderTest.operateDouble(1.0);
By the way, you don't need to call EasyMock.expectLastCall. It is only useful if you expect a void method to be called multiple times, for example:
mock.operateCar(EasyMock.anyObject(Car.class));
EasyMock.expectLastCall().times(3);

TestNg Assert.AssertTrue Always returns False - Selenium Webdriver

I have a util function as below:
public static boolean isWebElementEnabled(WebElement element) {
try {
return element.isEnabled();
} catch (Exception exx) {
return false;
}
}
public static boolean chkForThisElement(WebElement myElement) {
try {
return myElement.isDisplayed();
} catch (Exception e) {
// TODO Auto-generated catch block
return false;
}
}
I call it like this in the base class:
public static boolean isusernameBoxEnabled = isWebElementEnabled(unameBox);
public static boolean ispWordBoxEnabled = isWebElementEnabled(pwordBox);
public static boolean issubmitBtnEnabled = isWebElementEnabled(submitBtn);
public static boolean isctrsDrpdwnEnabled = isWebElementEnabled(multyCts);
When I test it in the Test class, it always returns false. I tried diff ways of testing for existence, but it only returns false.
#Test(priority=1)
public void verifyLoginpagecontrols() {
Assert.assertTrue(isusernameBoxEnabled);
Assert.assertTrue(ispWordBoxEnabled);
Assert.assertTrue(issubmitBtnEnabled);
Assert.assertTrue(isctrsDrpdwnEnabled);
}
i found a solution that works cool with Ff and Chromre driver nevertheless fails in Htmlunit driver.
Solution for the above problem -
// Initialize the home page elements and then check for assertions;
homePagePO searchPage = PageFactory.initElements(driver,
homePagePO.class);
Assert.assertTrue(chkForThisElement(searchPage.AccManagerHref));
Assert.assertTrue(chkForThisElement(searchPage.disHref));
Sorry to say but I find several things wrong with your code :-
You have not initialized the page factory. That is the reason why you are getting the null error.
In your comment, you have said that you are finding elements by using #findBy. But why have you decalared the WebElement as static?.
Why have you declared isusernameBoxEnabled and related boolean variables as global variables. You could use the isWebElementEnabled() function in your assert directly.
Basically your isWebElementEnabled() is not useful at all if you are using page factory.
Because the moment you use unameBox, selenium looks for the element in the webpage and if not found returns a noSuchElement Exception. So unameBox wont reach isWebElementEnabled() if it is not found in the webpage.
You said there is a base class and Test class. But I don't understand how your code works if there are different classes because you have not made a reference to static variable as Assert.assertTrue(baseClass.isusernameBoxEnabled). So I am assuming that you have only one class and different methods.
Try the following code :-
public class Base {
#FindBy()
WebElement unameBox;
#FindBy()
WebElement pwordBox;
#FindBy()
WebElement submitBtn;
#FindBy()
WebElement multyCts;
}
public class Test {
#Test(priority=1)
public void verifyLoginpagecontrols() {
//initialize page factory
Base base = PageFactory.initElements(driver, Base.class);
Assert.assertTrue(base.unameBox.isEnabled());
Assert.assertTrue(base.pwordBox.isEnabled());
Assert.assertTrue(base.submitBtn.isEnabled());
Assert.assertTrue(base.multyCts.isEnabled());
}
}
Hope this helps you.

Resources