Junit expected value exception - java

I am writing a test to test my repository. I noticed that the return expected value matches the actual value except that the actual value is wrapped within "<>".
I do not know why this is happening.
#ExperimentalCoroutinesApi
#RunWith(AndroidJUnit4::class)
#Config(sdk = [Build.VERSION_CODES.O_MR1])
class MovieRepositoryTest{
#get:Rule
var instantExecutorRule = InstantTaskExecutorRule()
private val movie1 = MovieEntity("Title1", "https://movie1.jpg", 3, "Movie1Overview", "Jan 2021")
private val movie2 = MovieEntity("Title2", "https://movie2.jpg", 3, "Movie2Overview", "Jan 2022")
private val movie3 = MovieEntity("Title3", "https://movie3.jpg", 3, "Movie2Overview", "Jan 2023")
private val remoteTasks = mutableListOf(movie3).sortedBy { it.id }
private val localTasks = mutableListOf(movie1, movie2).sortedBy { it.id }
private lateinit var tasksRemoteDataSource: FakeDataSource<MovieEntity>
private lateinit var tasksLocalDataSource: FakeDataSource<MovieEntity>
private lateinit var moviesRepository: MoviesRepoInterface
#Before
fun createRepository() {
tasksRemoteDataSource = FakeDataSource(remoteTasks.toMutableList())
tasksLocalDataSource = FakeDataSource(localTasks.toMutableList())
moviesRepository = MovieRepository(tasksRemoteDataSource, tasksLocalDataSource)
}
#Test
fun getRemoteMovies_RequestAllMovie()= runBlockingTest{
val movies = moviesRepository.getMovies(false, ApplicationProvider.getApplicationContext())
assertEquals(movies.getOrAwaitValue(), IsEqual<List<MovieEntity>>(localTasks))
}
}
Error
java.lang.AssertionError:
Expected :[com.darotapp.cornflix.data.local.database.MovieEntity#3843fe46, com.darotapp.cornflix.data.local.database.MovieEntity#1b40b010]
Actual :<[com.darotapp.cornflix.data.local.database.MovieEntity#3843fe46, com.darotapp.cornflix.data.local.database.MovieEntity#1b40b010]>
The data class for the table is below
Table
#Entity
data class MovieEntity(
var title: String?,
var movieImage:String?,
var rating:Int?,
var overView:String?,
var releaseDate:String?
): Serializable {
operator fun component1(): String? = title
operator fun component2(): String? = movieImage
operator fun component3(): Int? = rating
operator fun component4(): String? = overView
operator fun component5(): String? = releaseDate
#PrimaryKey()
var id: Int = 0
var favourite:Boolean = false
var movieId:String? = ""
}

I finally figured it out. The problem was using IsEqual. I was able to correct this with the code below.
val movies = moviesRepository.getMovies(false, ApplicationProvider.getApplicationContext())
assertEquals(movies?.value, Matchers.equalTo(localTasks))

Related

Why nested class call like this "val statusData:StatusData?=StatusData()"?

Why nested class call in this way val statusData:StatusData?=StatusData().
class NestedModel{
var id: String? = null
val statusData:StatusData?=StatusData() // Like this
class StatusData {
var internal_status: String? = null
var ot_code: String? = null
}
}
Your question is not understandable. But i thing your question is this. Why we can not call StatusData() from nestedModel object. For this we use "inner class" key word.
Example:
fun main() {
val nestedModel = NestedModel()
val statusData = nestedModel.StatusData()
}
class NestedModel {
var id: String? = null
inner class StatusData {
var internal_status: String? = null
var ot_code: String? = null
}
}

Bluetooth LE - How do i get Advertisement Interval in milliseconds?

I have to get the Advertisement Interval in milliseconds. I used result.periodicAdvertisingInterval but this returns 0. I have to implement something like this:
private val scanCallback = object : ScanCallback(){
#RequiresApi(Build.VERSION_CODES.N)
#SuppressLint("MissingPermission", "NotifyDataSetChanged")
override fun onScanResult(callbackType: Int, result: ScanResult) {
val scanJob = CoroutineScope(Dispatchers.Main).launch {
val tag = deviceMap.computeIfAbsent(result.device.address) {
val newTag = BleTag(result.device.name ?: "Unbekannt", result.device.address, result.rssi , result.scanRecord?.bytes, "")
deviceList.add(newTag)
newTag
}
tag.name = result.device.name ?: "Unbekannt"
tag.rssi = result.rssi
tag.advertisementData = result.scanRecord?.bytes
}
deviceList.sortBy {result.rssi }
recyclerView.adapter?.notifyDataSetChanged()
menu.findItem(R.id.count).title = "Geräte: " + deviceList.size
super.onScanResult(callbackType, result)
}
override fun onScanFailed(errorCode: Int) {
super.onScanFailed(errorCode)
Log.e("Scan failed","")
}
}
This result is obtained by subtracting the timestamps of two consecutive advertisements of the same device.

Cant fill json array to array list android development

I was trying to send json array from my web into an arraylist in a class with volley libarary
Here is array that i want to be filled
i want to replace dummy data in function getBestSelling() with data from web
Filename = DummyDataSource.kt (it is just plain kotlin class)
fun getBestSelling(): Observable<ArrayList<ProductEntity>> {
val dummy1 = ProductEntity(name = "Bell Pepper Red", description = "1kg, Priceg",
price = 20000,
picture = R.drawable.iv_pepper_red,
id = 5
)
val dummy2 = ProductEntity(name = "Beef bone", description = "1kg, Priceg",
price = 25000,
picture = R.drawable.iv_beef_bone,
id = 6
)
val dummy3 = ProductEntity(name = "Boiler Chicken", description = "1kg, Priceg",
price = 15000,
picture = R.drawable.iv_boiler_chicken,
id = 7
)
val dummy4 = ProductEntity(name = "Ginger", description = "250gm, Priceg",
price = 22000,
picture = R.drawable.iv_ginger,
id = 4
)
val data = listOf(dummy1, dummy2, dummy3, dummy4)
return Observable.just(ArrayList(data))
}
Here are what i do to get array filled
fun getBestSelling(): Observable<ArrayList<ProductEntity>> {
var url:String="http:// 192.168.56.1/toko-online/mobile/pro_kategori.php"
var rq : RequestQueue = Volley.newRequestQueue(this)
var data = ArrayList<ProductEntity>()
var js = JsonArrayRequest(Request.Method.GET,url,null, Response.Listener{ response ->
for (x in 0..response.length()-1){
data.add(ProductEntity(response.getJSONObject(x).getInt("id"),
response.getJSONObject(x).getInt("id"),response.getJSONObject(x).getString("name"),
response.getJSONObject(x).getString("url"),response.getJSONObject(x).getString("description"),
response.getJSONObject(x).getInt("price"),response.getJSONObject(x).getInt("stock"),
response.getJSONObject(x).getInt("category_id")))
}
}, Response.ErrorListener { error ->
Toast.makeText(this,error.message,Toast.LENGTH_LONG).show()
})
rq.add(js)
return Observable.just(data)
}
The error come from line " var rq : RequestQueue = Volley.newRequestQueue(this)"
it says
"Type mismatch: inferred type is DummyDataSource but Context! was expected"
so i copied this code
fun getdata(): Observable<ArrayList<ProductEntity>> {
var url:String="http:// 192.168.56.1/toko-online/mobile/pro_kategori.php"
var rq : RequestQueue = Volley.newRequestQueue(this)
var data = ArrayList<ProductEntity>()
var js = JsonArrayRequest(Request.Method.GET,url,null, Response.Listener{ response ->
for (x in 0..response.length()-1){
data.add(ProductEntity(response.getJSONObject(x).getInt("id"),
response.getJSONObject(x).getInt("id"),response.getJSONObject(x).getString("name"),
response.getJSONObject(x).getString("url"),response.getJSONObject(x).getString("description"),
response.getJSONObject(x).getInt("price"),response.getJSONObject(x).getInt("stock"),
response.getJSONObject(x).getInt("category_id")))
}
}, Response.ErrorListener { error ->
Toast.makeText(this,error.message,Toast.LENGTH_LONG).show()
})
rq.add(js)
return Observable.just(data)
}
into oncreate in the main activity. But because of that i cant fill array within getBestSelling() in DummyDataSource.kt because the function getdata() only return data to oncreate
Is there any way to make data go to getBestSelling() in DummyDataSource.kt ?
Move your function back out of onCreate and replace "this" with a context reference (requreContext() or create a Context var in onCreate to reference)

Codec not found for requested operation: [map<varchar, int> <-> java.util.Map]; issue Apache Cassandra

I have a table with the fields
CREATE TABLE app_category_agg (
category text,
app_count int,
sp_count int,
subscriber_count int,
window_revenue bigint,
top_apps frozen <list<map<text,int>>>,
PRIMARY KEY (category)
);
when I try to map it to kotlin model
#Table("app_category_agg")
class AppCategoryAggData {
#PrimaryKeyColumn(name = "category", ordinal = 0, type = PrimaryKeyType.PARTITIONED)
lateinit var category: String
#Column("app_count")
var appCount: Int = 0
#Column("sp_count")
var spCount: Int = 0
#Column("subscriber_count")
var subscriberCount: Int = 0
#Column("window_revenue")
var windowRevenue: Long = 0
#Column("top_apps")
var topApps: List<Any> = arrayListOf()
}
interface AppCategoryAggRepository: CassandraRepository<AppCategoryAggData, String> {
#Query(value = "SELECT * FROM analytics_info.app_category_agg")
fun findAllAppCategoryAggData(): List<AppCategoryAggData>
}
I get this error
Query; CQL [SELECT * FROM analytics_info.app_category_agg]; Codec not found for requested operation: [map<varchar, int> <-> java.util.Map]; nested exception is com.datastax.driver.core.exceptions.CodecNotFoundException: Codec not found for requested operation: [map<varchar, int> <-> java.util.Map]
how can I resolve it? I read about making codecs but it's not very much clear to me
I've created a table with your structure, and populated it with sample data:
insert into app_category_agg (category, app_count, sp_count, subscriber_count, window_revenue, top_apps)
values('test', 2, 1, 10, 100, [{'t1':1, 't2':2}]);
For object mapper from the Java driver 3, the working code is following.
Class declaration:
import com.datastax.driver.mapping.MappingManager
import com.datastax.driver.mapping.annotations.Column
import com.datastax.driver.mapping.annotations.PartitionKey
import com.datastax.driver.mapping.annotations.Table
#Table(keyspace = "test", name = "app_category_agg")
class AppCategoryAggData {
#PartitionKey
lateinit var category: String
#Column(name = "app_count")
var appCount: Int = 0
#Column(name = "sp_count")
var spCount: Int = 0
#Column(name = "subscriber_count")
var subscriberCount: Int = 0
#Column(name = "window_revenue")
var windowRevenue: Long = 0
#Column(name = "top_apps")
var topApps: List<Map<String, Int>> = emptyList()
override fun toString(): String {
return "AppCategoryAggData(category='$category', appCount=$appCount, spCount=$spCount, subscriberCount=$subscriberCount, windowRevenue=$windowRevenue, topApps=$topApps)"
}
}
Main function - it first inserts data from Kotlin code, and then read the data that I pre-inserted:
import com.datastax.driver.core.Cluster
object KtTestObjMapper {
#JvmStatic
fun main(args: Array<String>) {
val cluster = Cluster.builder()
.addContactPoint("10.101.34.176")
.build()
val session = cluster.connect()
val manager = MappingManager(session)
val mapper = manager.mapper(AppCategoryAggData::class.java)
val appObj = AppCategoryAggData()
appObj.category = "kotlin"
appObj.appCount = 5
appObj.spCount = 10
appObj.subscriberCount = 50
appObj.windowRevenue = 10000
appObj.topApps = listOf(mapOf("t2" to 2))
mapper.save(appObj)
val obj2 = mapper.get("test")
print("obj2=$obj2")
session.close()
cluster.close()
}
}
When I run this code, I receive following output:
Object from =AppCategoryAggData(category='test', appCount=2, spCount=1, subscriberCount=10, windowRevenue=100, topApps=[{t1=1, t2=2}])
and when I select data from table using cqlsh, I see that data were inserted by Kotlin:
cqlsh:test> SELECT * from app_category_agg ;
category | app_count | sp_count | subscriber_count | top_apps | window_revenue
----------+-----------+----------+------------------+----------------------+----------------
test | 2 | 1 | 10 | [{'t1': 1, 't2': 2}] | 100
kotlin | 5 | 10 | 50 | [{'t2': 2}] | 10000
(2 rows)
The full code is in my repository. The one drawback of this solution is that it's based on the Java driver 3.x that is previous major release of the driver. If you don't have strict requirement for it, it's recommended to use latest major release - 4.x, that works with both Cassandra & DSE, and has a lot of new functionality.
Although the object mapper in new version works differently - instead of run-time annotations, the compile annotations are used, so code looks differently, and we need to configure compilation process differently, and it could be more complicated compared to driver 3.x, but code itself could be simpler (full code is here).
We need to define data class (entity):
#Entity
#CqlName("app_category_agg")
data class AppCategoryAggData(
#PartitionKey var category: String,
#CqlName("app_count") var appCount: Int? = null,
#CqlName("sp_count") var spCount: Int? = null,
#CqlName("subscriber_count") var subscriberCount: Int? = null,
#CqlName("window_revenue") var windowRevenue: Long? = null,
#CqlName("top_apps") var topApps: List<Map<String, Int>>? = null
) {
constructor() : this("")
}
Define the DAO interface with 2 operations (insert and findByCategory):
#Dao
interface AppCategoryAggDao {
#Insert
fun insert(appCatAgg: AppCategoryAggData)
#Select
fun findByCategory(appCat: String): AppCategoryAggData?
}
Define the Mapper to obtain the DAO:
#Mapper
interface AppCategoryMapper {
#DaoFactory
fun appCategoryDao(#DaoKeyspace keyspace: CqlIdentifier?): AppCategoryAggDao?
}
And use it:
object KtTestObjMapper {
#JvmStatic
fun main(args: Array<String>) {
val session = CqlSession.builder()
.addContactPoint(InetSocketAddress("10.101.34.176", 9042))
.build()
// get mapper - please note that we need to use AppCategoryMapperBuilder
// that is generated by annotation processor
val mapper: AppCategoryMapper = AppCategoryMapperBuilder(session).build()
val dao: AppCategoryAggDao? = mapper.appCategoryDao(CqlIdentifier.fromCql("test"))
val appObj = AppCategoryAggData("kotlin2",
10, 11, 12, 34,
listOf(mapOf("t2" to 2)))
dao?.insert(appObj)
val obj2 = dao?.findByCategory("test")
println("Object from =$obj2")
session.close()
}
}
The change compared to Java is that we need to use the generated class AppCategoryMapperBuilder to obtain the instance of AppCategoryMapper in:
val mapper: AppCategoryMapper = AppCategoryMapperBuilder(session).build()

How to Extract vector in session?

I have saved vector in session and I want to use random value from the vector but dont know how to extract value in session.
Errors:
'httpRequest-6' failed to execute: Vector(437420, 443940, 443932,
437437, 443981, 443956, 443973, 443915, 437445) named 'termIds' does
not support .random function
And
In 2nd scenario It passes vector in get request like this way, http://someurl/api/thr/Vector(435854)/terms/Vector(437420, 443940,
443932, 437437, 443981, 443956, 443973, 443915, 437445)
instead of using
http://someurl/api/thr/435854/terms/443973
::Here is my script::
class getTerm extends Simulation {
val repeatCount = Integer.getInteger("repeatCount", 1).toInt
val userCount = Integer.getInteger("userCount", 1).toInt
val turl = System.getProperty("turl", "some url")
val httpProtocol = http
.baseURL("http://" + turl)
val headers_10 = Map("Content-Type" -> """application/json""")
var thrIds = ""
var termIds = ""
// Scenario - 1
val getTerms = scenario("Scn 1")
.exec(http("list_of_term")
.get("/api/abc")
.headers(headers_10)
.check(jsonPath("$[*].id")
.findAll.saveAs("thrIds"))
)
.exec(http("get_all_terms")
.get("""/api/thr/${thrIds.random()}/terms""")
.headers(headers_10)
.check(jsonPath("$[*].id")
.findAll.saveAs("termIds"))
)
.exec(session => {
thrIds = session("thrIds").as[Long].toString
termIds = session("termIds").as[Long].toString
println("***************************************")
println("Session ====>>>> " + session)
println("Ths ID ====>>>> " + thrIds)
println("Term ID ====>>>> " + termIds)
println("***************************************")
session}
)
// Scenario - 2
// Want to extract vectors here and pass its value into get call
val getKnownTerms = scenario("Get Known Term")
.exec(_.set("thrIds", thrIds))
.exec(_.set("termIds", termIds))
.repeat (repeatCount){
exec(http("get_k_term")
.get("""/api/thr/${thrIds}/terms/${termIds.random()}""")
.headers(headers_10))
}
val scn = List(getTerms.inject(atOnceUsers(1)), getKnownTerms.inject(nothingFor(20 seconds), atOnceUsers(userCount)))
setUp(scn).protocols(httpProtocol)
}
Here is the solution which may help others.
class getTerm extends Simulation {
val repeatCount = Integer.getInteger("repeatCount", 1).toInt
val userCount = Integer.getInteger("userCount", 1).toInt
val turl = System.getProperty("turl", "some url")
val httpProtocol = http
.baseURL("http://" + turl)
val headers_10 = Map("Content-Type" -> """application/json""")
// Change - 1
var thrIds: Seq[String] = _
var termIds: Seq[String] = _
// Scenario - 1
val getTerms = scenario("Scn 1")
.exec(http("list_of_term")
.get("/api/abc")
.headers(headers_10)
.check(jsonPath("$[*].id")
.findAll
.transform { v => thrIds = v; v }
.saveAs("thrIds"))
)
.exec(http("get_all_trms")
.get("""/api/thr/${thrIds.random()}/terms""")
.headers(headers_10)
.check(jsonPath("$[*].id")
.findAll
.transform { v => termIds = v; v }
.saveAs("termIds"))
)
// Scenario - 2
val getKnownTerms = scenario("Get Known Term")
.exec(_.set("thrIds", thrIds))
.exec(_.set("termIds", termIds))
.repeat (repeatCount){
exec(http("get_k_term")
.get("""/api/thr/${thrIds.random()}/terms/${termIds.random()}""")
.headers(headers_10))
}
val scn = List(getTerms.inject(atOnceUsers(1)), getKnownTerms.inject(nothingFor(20 seconds), atOnceUsers(userCount)))
setUp(scn).protocols(httpProtocol)
}

Categories

Resources